Re: Power arithmetic function to C#



"SunYour" <sunyour@xxxxxxxxxxx> wrote in message
news:1143700972.958565.279730@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Thank you all, here is my c# contribution:

And thank you for telling us what you did with our answers.


public static double MathPower(double basenum, double exponent)
{
if(exponent == 0)
return 1;
else if(basenum == 0 && exponent > 0)
return 0;
else if((basenum - (int)basenum) == 0
&& Math.Abs(exponent) <= int.MaxValue
)

Three things.

First, instead of casting a double to int, your intent would be
expressed clearer by calling Floor(). Unfortunately, Frac() is not
a standard function.

Second, you are depending on == and <= having higher priorities than
&&. Extra parentheses are warranted.

Third, how exact do you want your integer check? Comparing doubles
to integer constants is a very inexact science. You are safe in this
case, because there is a fallback to a different computation method
that does the right thing, but the usual way is to check for a very
small difference (abs(x-y)<epsilon) rather than outright equality.


return Math.Pow(basenum, (int)Math.Truncate(exponent));

Truncate is not in Math. I take it you mean Decimal.Truncate()?


else
return Math.Exp(exponent * Math.Log(basenum, Math.E));

Log()'s base defaults to e if you leave it off. This matches Exp();
its base is also e.

}

Groetjes,
Maarten Wiltink


.