gpt4 book ai didi

Sin 和 ToRadians 的 Java 奇怪行为

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:53:08 25 4
gpt4 key购买 nike

我被赋予了使用 java 生成 Sin 表的任务,但是对于某些输入值,我似乎得到了一些非常奇怪的结果。我正在使用下面的

System.out.println("| sin(" + currentPoint + ") = " + Math.sin(Math.toRadians(currentPoint)));

其中 (int) currentPoint 是一个以度数 为单位的值(例如 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

我错过了什么吗?

最佳答案

您正在处理 float ,寻找精确答案并不适用于所有值。看一眼 What Every Computer Scientist Should Know About Floating-Point Arithmetic .您希望您的测试在某个增量范围内等同于您的期望。请注意,您得到的答案非常接近。它以比特的形式表达值(value),这让您感到厌烦。

来自链接:

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 奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3961900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com