开发者

How do you write exp(a/b) in C#?

开发者 https://www.devze.com 2023-01-11 07:25 出处:网络
I am calculating a formula and would like to know how to writ开发者_如何转开发e 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 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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号