tags:

views:

177

answers:

2

I am calculating a formula and would like to know how to write exp(a/b) in C#. I heard about math.exp, but it takes only one parameter.

+8  A: 

As it says in the docs for Math.Exp,

Use the Pow method to calculate powers of other bases.

http://msdn.microsoft.com/en-us/library/system.math.pow.aspx

If you're passing the result of a/b (that is, a divided by b), then that result is a single value, which could be passed to Math.Exp.

Daniel Earwicker
+7  A: 

Like Daniel already mentioned in his answer, use Math.Exp.

With my answer, I'd like to point out a little pitfall that you can avoid in your situation.

If you're going to call Math.Exp like you mentioned in your question, i.e. Math.Exp(a/b), where a and b are two integers, and not variables, don't forget to cast the numerator to double:

Math.Exp((double)1/2);

If you don't do that, the division will be made with two ints, resulting in a loss of precision (see the comments in the code):

Math.Exp(1/2); //results in 1, since 1/2 = 0 and e^0 = 1
Math.Exp((double)1/2); //results in 1.64872127070013, since (double)1/2 = 0.5

As Daniel correctly mentioned in a comment to this answer, the cast to double can be omitted once you define a and b as double, and use both variables for the division in Math.Exp:

double a = 1;
double b = 2;
Math.Exp(a/b);
Giu
NB. only add the cast if `a` and `b` are not of type `double` already.
Daniel Earwicker
@Daniel True, thanks. I've updated my answer to include your remark, though I was assuming he would call it without defining variables
Giu