tan 45 gives me 0.9999

荒凉一梦 提交于 2019-12-19 06:37:10

问题


Why does tan 45(0.7853981633974483 in radian) give me 0.9999? What's wrong with the following code?

System.out.println(Math.tan(Math.toRadians(45.0)) );

I don't think there's any typo in here.

So what's the solution here?


回答1:


Floating point calculations will often lead to such inaccuracies. The problem is that numbers cannot be accurately represented within a fixed number of bits.

To give you another example (in decimal), we all agree that 3 * (1/3) = 1. However, if your calculator only has 4 decimal places, 1/3 would be represented as 0.3333. When that's multiplied with 3, you would get 0.9999 not 1.

As further information, floating points on most systems are usually represented using the IEEE754 standard. You could search for it, or refer the Wikipedia page for more details. IEEE floating point




回答2:


The closest double to pi/4 is exactly 0x1.921fb54442d18p-1. The tangent of this double, to more bits than you need, is 0x1.fffffffffffff72cece67p-1. Rounding to the nearest double gives you exactly 0x1.fffffffffffffp-1 because 0x1.fffffffffffff72cece67p-1 is less than 0x1.fffffffffffff8p-1.




回答3:


Use this

double radians = Math.toRadians(45.0);

System.out.format("The tangent of 45.0 degrees is %.4f%n", Math.tan(radians));



回答4:


That's probably because tan(45) is 1, and the rest is a rounding error. Floating point calculations are highly unlikely to give you accurate results, due to how floating point calculations work.



来源:https://stackoverflow.com/questions/13775550/tan-45-gives-me-0-9999

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!