How do you write exp(a/b) in C#?
I am calculating a formula and would like to know how to writ开发者_如何转开发e exp(a/b)
in C#.
I heard about math.exp
, but it takes only one parameter.
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.
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 int
s, 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);
精彩评论