Is there a Math API for Pow(decimal, decimal)

41,789

Solution 1

One of the multipliyers is a rate : 1/rate^(days/365).

The reason there is no decimal power function is because it would be pointless to use decimal for that calculation. Use double.

Remember, the point of decimal is to ensure that you get exact arithmetic on values that can be exactly represented as short decimal numbers. For reasonable values of rate and days, the values of any of the other subexpressions are clearly not going to be exactly represented as short decimal values. You're going to be dealing with inexact values, so use a type designed for fast calculations of slightly inexact values, like double.

The results when computed in doubles are going to be off by a few billionths of a penny one way or the other. Who cares? You'll round out the error later. Do the rate calculation in doubles. Once you have a result that needs to be turned back into a currency again, multiply the result by ten thousand, round it off to the nearest integer, convert that to a decimal, and then divide it out by ten thousand again, and you'll have a result accurate to four decimal places, which ought to be plenty for a financial calculation.

Solution 2

Here is what I used.

output = (decimal)Math.Pow((double)var1, (double)var2);

Now I'm just learning but this did work but I don't know if I can explain it correctly.

what I believe this does is take the input of var1 and var2 and cast them to doubles to use as the argument for the math.pow method. After that have (decimal) in front of math.pow take the value back to a decimal and place the value in the output variable.

I hope someone can correct me if my explination is wrong but all I know is that it worked for me.

Solution 3

I know this is an old thread but I'm putting this here in case someone finds it when searching for a solution. If you don't want to mess around with casting and doing you own custom implementation you can install the NuGet DecimalMath.DecimalEx and use it like DecimalEx.Pow(number,power).

Solution 4

Well, here is the Wikipedia page that lists current C# numerics libraries. But TBH I don't think there is a lot of support for decimals

http://en.wikipedia.org/wiki/List_of_numerical_libraries

It's kind of inappropriate to use decimals for this kind of calculation in general. It's high precision yes - but it's also low range. As the MSDN docs state it's for financial/monetary calculations - where there isn't much call for POW unfortunately!

Of course you might have a specific problem domain that needs super high precision and all numbers are within 10(28) - 10(-28). But in that case you will probably just need to write your own series calculator such as the one linked to in the comments to the question.

Share:
41,789
Maxime ARNSTAMM
Author by

Maxime ARNSTAMM

About Me

Updated on May 28, 2020

Comments

  • Maxime ARNSTAMM
    Maxime ARNSTAMM almost 4 years

    Is there a library for decimal calculation, especially the Pow(decimal, decimal) method? I can't find any.

    It can be free or commercial, either way, as long as there is one.

    Note: I can't do it myself, can't use for loops, can't use Math.Pow, Math.Exp or Math.Log, because they all take doubles, and I can't use doubles. I can't use a serie because it would be as precise as doubles.

  • James Gaunt
    James Gaunt almost 13 years
    I assume the point here is to gain additional precision over that provided by double... otherwise why use decimals at all?
  • spender
    spender almost 13 years
    You could equally rephrase this answer as "What is the point of the Decimal type?"
  • Maxime ARNSTAMM
    Maxime ARNSTAMM almost 13 years
    i play with money, obviously i won't use integers.
  • Brian
    Brian almost 13 years
    The OP later mentioned that he is using Decimals because he is working with money. In that situation, I think he's better off following Eric Lippert's advice.
  • James Gaunt
    James Gaunt almost 13 years
    Fair enough - that fact he was doing financial calculations was added at a later point. Obviously there is no need for the kind of accuracy he's talking about with financial calculations.
  • configurator
    configurator almost 13 years
    Doesn't decimal provide more precision? The 64 extra bits it gets have to help a little...
  • Eric Lippert
    Eric Lippert almost 13 years
    @configurator: The answer to your question is "yes". Your statement following the question does not follow logically from the answer to the question. Why does having twice the number of bits help in a financial problem that only has to be accurate to, say, the tenth of a penny? Clearly the question is about a compounded-daily interest calculation; are there compounded-daily banking problems that require more than 15 decimal digits of precision when working out today's interest? If today's interest is $10.92857924858 in double and $10.9285792485820968039468095 in decimal, does it matter?
  • configurator
    configurator almost 13 years
    When I worked on compound daily interests we were required to be accurate to within 12 decimal digits, which I personally feel is dangerously close to double's limits. (Never mind that the 12 digits were completely arbitrary and 'accurate' meant 'same value as the seriously flawed old VB3 implementation' so we needed to introduce calculation errors...)
  • Eric Lippert
    Eric Lippert almost 13 years
    @configurator: Wow, that sounds like fun. I am not an expert in numerical methods by any means, but I did a reasonable amount of both study and some professional work early in my career, and it's been my experience that unless there is some "stiffness" in the partial differential equation you're solving, accuracy to twelve places is unnecessary. Was there some numerical-methods-based justification for the twelve-figure requirement?
  • configurator
    configurator almost 13 years
    @Eric: They were pension calculations done on a daily basis for 40-50 years in the typical case, so any slightest error can combine quite easily. Add to that that the final results were aggregated (wrongly!) across companies to sum their total pension funds, and you need accuracy far beyong 3 decimal points...
  • marcelo-ferraz
    marcelo-ferraz over 10 years
    So I had found myself in a situation whereas my precision demanded close to 32 numbers before the dot. I had found that the usage of decimals with 28 numbers before the dot and 28 after, made that possible. In my case, I altered the whole set of equations to fit inside those 56 numbers. Well, my point is, sometimes we really need more than just the framework can achieve by itself, and for that we have go a little further than we'd expect. Use log, cos, sin. Probably someone might had bumped into your situation and have a mathematic solution to it. Good luck
  • komodosp
    komodosp almost 9 years
    "Who cares if it's off by a few billionths, you'll round out the error later" - Sometimes it does matter. e.g. if you get a value of 2.4999999998 when you were expecting 2.5 and want to round it to the nearest integer, now you're getting 2 instead of 3, which is incorrect.
  • Eric Lippert
    Eric Lippert almost 9 years
    @colmde: Exactly my point. By rounding you are saying that you are willing to take on an error many, many orders of magnitude larger than the error induced by the computation process. If a large rounding introduces too much error after a small error is introduced then you should not be doing the large rounding in the first place.
  • Juan M. Elosegui
    Juan M. Elosegui almost 9 years
    @EricLippert, what do you mean by short decimal?
  • Eric Lippert
    Eric Lippert over 8 years
    @jmelosegui: It was not clear what I meant. What I meant was that if you want to represent 123 dollars and 45 cents then use decimal; the pennies are exact. Computations that produce values involving significant digits to the millionth or a billionth of a cent are unlikely to be meaningful in the dollars-and-cents domain.
  • John
    John about 7 years
    The shifting operator (<<) analogue is somewhat relevant though, and that's a special case of the power operator.
  • Squazz
    Squazz over 6 years
    This is also what I always end up doing ;)
  • Bob Vale
    Bob Vale about 6 years
    Yes I did that till the result was outside of the range of decimal and I ended up with an overflow exception
  • Voo
    Voo about 5 years
    While the answer is true in this case, I can think of use cases where having Math.Pow(decimal, decimal) seems rather necessary to me. For example I have to validate that a value will fit inside a decimal(p,s) field in the database. The simplest way to do that is to use 10^(p-s) as the upper bound. Trying to do that with doubles will not work in all cases (it's not that trivial to figure out what the first power is for which this fails)
  • Patrick Kelly
    Patrick Kelly over 3 years
    @EricLippert It's used in the calculation of geometric mean, which is used in finance, such as the FT30 index or the RPIJ inflation index. There absolutely is reason to use this with Decimal. Claiming there isn't any reason is irresponsible. "I'm not aware of any" is a much more honest position.
  • Patrick Kelly
    Patrick Kelly over 3 years
    This isn't true. Pow is used in the calculation of things like the geometric mean, which is used to calculate the FT30 index, FPIJ inflation index, and more. It's much more honest to say "I'm not aware of any case" than to claim it isn't used at all.
  • James Gaunt
    James Gaunt over 3 years
    Wow - 9 years ago - blast from the past. Just re-reading the post and I can't see anywhere I claim "it isn't used at all". I just say there isn't much call for it - which is true. But thanks for the comment.