简体   繁体   English

Java Math.cos(Math.toRadians( <angle> ))返回奇怪的值

[英]Java Math.cos(Math.toRadians(<angle>)) returns weird values

I've got a little Problem with the Math.cos() method. 我在Math.cos()方法上遇到了一些问题。 I know, I have to convert the angle to Radians before using Math.cos() . 我知道,在使用Math.cos()之前,必须将角度转换为弧度。 But if I just do: 但是,如果我只是这样做:

System.out.println(Math.cos(Math.toRadians(90));

It outputs: 6.123233995736766E-17 输出:6.123233995736766E-17

Math.sin() is working well. Math.sin()运行良好。

From trigonometry: 从三角学:

sin x ~= x, for small values of x
sin x = cos x+pi/2

Because pi/2 can't be represented exactly in IEEE-754 Floating point, it means, that it must be off by some value x, ie it is represented by pi/2 +- x, where x < the least significant bit in the floating point system. 由于pi / 2不能在IEEE-754浮点数中精确表示,因此,它必须与某个值x偏离,即用pi / 2 +-x表示,其中x <的最低有效位浮点系统。 Which in this case is 2^-53 = 1.1102e-16. 在这种情况下为2 ^ -53 = 1.1102e-16。

In this particular case x ~= 6.123233995736766E-17, which is about 55% of the maximum error. 在此特定情况下,x〜= 6.123233995736766E-17,大约是最大误差的55%。 So, it's a rather good result... 所以,这是一个相当不错的结果...

See the Javadoc. 请参阅Javadoc。 "The conversion from degrees to radians is generally inexact." “从度到弧度的转换通常是不精确的。”

The value is very close to the correct result. 该值非常接近正确的结果。 It seems like a loss of precision in the floating point operations of transforming degrees to radians. 在将度数转换为弧度的浮点运算中,似乎失去了精度。

Standing temporarily on a soapbox, I think people are confused about the concepts of accuracy versus precision . 我认为人们暂时站在肥皂盒上,对精度与精度的概念感到困惑。 Is this an issue as some have said? 正如某些人所说,这是一个问题吗? Is it a problem? 这是个问题吗? A bug? 有毛病吗 Or is it an expected behavior of floating point arithmetic? 还是浮点算术的预期行为?

90 degrees is a number that is representable perfectly as an integer, even though a double. 90度是可以完美表示为整数(即​​使是双精度)的数字。 But pi/2 radians is a real number that is not represented exactly, so that representation will be slightly inaccurate. 但是pi / 2弧度是一个不能精确表示的实数,因此表示会有些不准确。 The loss is in accuracy. 损失在于准确性。 The fact is, this is expected behavior. 事实是,这是预期的行为。 We should never trust the least significant bits of a result. 我们永远不要相信结果的最低有效位。

Next, when we compute the value of a trigonometric function, there MAY be an additional loss of accuracy. 接下来,当我们计算三角函数的值时,可能会另外损失精度。 We don't get exactly the result that we know to be true in a symbolic sense. 从符号意义上讲,我们没有得到确切的结果。 Thus sin(pi/3) may not be exactly sqrt(3)/2, but then we can't represent sqrt(3)/2 exactly anyway. 因此sin(pi / 3)可能不完全是sqrt(3)/ 2,但是无论如何我们不能完全表示sqrt(3)/ 2。 All of this is expected, and is behavior that should be dealt with by good code, not trusting the LSBs of those numbers. 所有这些都是可以预期的,并且应该由良好的代码来处理行为,而不是相信这些数字的LSB。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM