问题描述
我被赋予了使用java来生成Sin表的任务,但是我似乎得到了一些非常奇怪的输入值。我使用下面的
I have been given the task of using java to produce a Sin table, however I seem to get some very weird results for some values of the input. I am using the below
System.out.println("| sin(" + currentPoint + ") = " + Math.sin(Math.toRadians(currentPoint)));
其中(int)currentPoint是度的值(例如90)
Where (int) currentPoint is a value in degrees (eg 90)
这些结果我觉得很奇怪
| sin(360) = -2.4492935982947064E-16
| sin(180) = 1.2246467991473532E-16
| sin(150) = 0.49999999999999994
| sin(120) = 0.8660254037844387
期待
sin(360) = 0
sin(180) = 0
sin(150) = 0.5
sin(120) = 0.866025404
我错过了什么吗?
推荐答案
您正在处理浮点数,寻找确切的答案对所有值都不起作用。看看
。您希望您的测试与某些增量中的预期相当。请注意,您得到的答案非常接近。它以咬住你的位表示价值。
You're dealing with floating point numbers, looking for exact answers isn't going to work for all values. Take a look atWhat Every Computer Scientist Should Know About Floating-Point Arithmetic. You want your tests to be equivalent to your expectations within some delta. Note that the answers you're getting are pretty close. It's expressing values in bits that's biting you.
从链接:
这篇关于Sin和ToRadians的Java奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!