Sin和ToRadians的Java奇怪行为 [英] Java Strange Behavior with Sin and ToRadians

查看:99
本文介绍了Sin和ToRadians的Java奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被赋予了使用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 at What 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.

从链接:


将无限多个实数压缩成有限数量的比特需要近似表示。尽管存在无限多个整数,但在大多数程序中,整数计算的结果可以以32位存储。相反,给定任何固定数量的位,大多数具有实数的计算将产生无法使用那么多位精确表示的量。因此,浮点计算的结果通常必须舍入,以便适应其有限表示。此舍入误差是浮点计算的特征。

Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits. In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.

这篇关于Sin和ToRadians的Java奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆