Java Math.cos()方法在预期时不返回0 [英] Java Math.cos() Method Does Not Return 0 When Expected

查看:369
本文介绍了Java Math.cos()方法在预期时不返回0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows 7 PC上使用Java(不确定是否重要)并在应该返回0的值(如pi / 2)上调用Math.cos()而不是返回小值,但是小值,除非我是误解,从零开始大于1 ulp。

Using Java on a Windows 7 PC (not sure if that matters) and calling Math.cos() on values that should return 0 (like pi/2) instead returns small values, but small values that, unless I'm misunderstanding, are much greater than 1 ulp off from zero.

Math.cos(Math.PI/2) = 6.123233995736766E-17
Math.ulp(Math.cos(Math.PI/2)) = 1.232595164407831E-32

这实际上是在1 ulp之内吗?我只是感到困惑?这是否是一个可以接受的解决这个小错误的包装方法?

Is this in fact within 1 ulp and I'm simply confused? And would this be an acceptable wrapper method to resolve this minor inaccuracy?

public static double cos(double a){
    double temp = Math.abs(a % Math.PI);
    if(temp == Math.PI/2)
        return 0;
    return Math.cos(a);
}


推荐答案

不要忘记 Math.PI / 2 是近似值。它不会完全 pi / 2,因此 cos(Math.PI / 2)的结果不会是完全 0. Math.cos 可能会返回计算 Math.PI返回的精确值的余弦的精确版本/ 2

Don't forget that Math.PI/2 is an approximation. It's not going to be exactly pi/2, so the result of cos(Math.PI/2) isn't going to be exactly 0. Math.cos may be returning a pretty accurate version of the cosine of the exact value returned by calculating Math.PI/2.

这篇关于Java Math.cos()方法在预期时不返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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