为什么Math.Tan(90)提供一个未定义的值? [英] Why does Math.Tan(90) provide a non-undefined value?
问题描述
使用Math.Tan()
时,我发现90度的结果不是不确定的.但是是 1.6331779e + 16
While working with Math.Tan()
I found that the result for 90 degree is not undefined. But is, inturn 1.6331779e+16
这是应用程序的屏幕截图
Here is the screenshot for the app
这是代码
// convert to degrees
angle = (Convert.ToDouble(op1) * Math.PI / 180);
// write the output
FinalResult.Text = Math.Tan(Convert.ToDouble(angle)).ToString();
为什么会有这样的行为?
Why is such behaviour, is it expected?
推荐答案
计算是使用不完美的浮点数完成的(不是Math.PI
始终可以完美地表示为十进制).
The calculation is done with floating point numbers which are not perfect (not that Math.PI
can ever be perfectly represented as a decimal anyways).
http://en.wikipedia.org/wiki/Floating_point
更具体地说..
如果想要四舍五入的结果,请检查输入中是否有类似>89.9999 && <90.00001
的内容.请勿将==
与浮点值一起使用.
If you want a rounded result then check the input for something like >89.9999 && <90.00001
. Don't use ==
with floating point values.
有关为何不将==
与浮点数一起使用的说明,请尝试运行以下示例:
For explanation of why not to use ==
with floating point numbers, try running this example:
var d = 0.2;
for(double k = 1.0; k<100; k++) {
var t = 0.2 * k;
t = t / k;
Console.WriteLine("{0} == {1} ==> {2}", d, t, d == t);
}
我们将0.2乘以整数,再将其除以相同的整数,然后与0.2进行比较.每次都应该是对的,对吧?它不是.很多时候它返回false.
We're multiplying 0.2 by a whole number, dividing it by the same whole number, and then comparing to 0.2. It should be true every time, right? It's not. Many times it returns false.
这篇关于为什么Math.Tan(90)提供一个未定义的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!