注意事项浮点 [英] Caveat floating point

查看:61
本文介绍了注意事项浮点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到三个Double类型的值x,y,z,使得(x + y)+ z == 1.0和x +(y + z)== 0.0.我正在尝试在Scala上解决此问题.此问题与浮点数学运算是否损坏?但我应该怎么做?找到这样的价值?有什么算法可以完成此任务?根据我的阅读,如果分母是2的幂,它将被转换为浮点而没有错误.我尝试过像0.5、1、0、0.25这样的值仍然没有成功.谁能帮我吗?

I need to find three values x,y,z of type Double, such that (x + y) + z == 1.0 and x + (y + z) == 0.0. I'm trying to solve this problem on Scala. This problem has to do with Is floating point math broken? but how i'm supposed to find such values? Is there any algorithm to complete this task? From what i have read, if the denominator is the power of two it is converted to floating point without an error. I tried values like 0.5, 1, 0, 0.25 still no success. Can anyone help me?

推荐答案

使用正确的x,y和z值,可以精确地获得1.0和0.0,而不必在比较中使用epsilon.我用Java编写了程序,但是该原理会延续到使用Double的IEEE 754 64位二进制浮点的其他语言.

With the right values of x, y, and z it is possible to get 1.0 and 0.0 exactly, without having to use an epsilon on the comparison. I wrote my program in Java, but the principle will carry across to other languages that use IEEE 754 64 bit binary floating point for Double.

public class Test {
  public static void main(String[] args) {
    double x = -Math.pow(2.0, 53);
    double y = 1.0;
    double z = -x;
    System.out.println((x + y) + z == 1.0);
    System.out.println(x + (y + z) == 0.0);
  }
}

[-Math.pow(2.0, 53), Math.pow(2.0, 53)]是所有整数值都可以精确表示的双精度范围.超出该范围,所有奇数必须四舍五入.将任一端的幅度增加1需要四舍五入,并且四舍五入以返回到自身.

[-Math.pow(2.0, 53), Math.pow(2.0, 53)] is the range of doubles in which all integer values are exactly representable. Outside that range, all odd numbers have to be rounded. Increasing the magnitude at either end by 1 requires rounding, and round to even goes back to itself.

x + y在范围内并且可以精确表示.将z加到结果中将得到1.0,即加法的实数结果.另一方面,y + z具有相等的符号,使得其大小太大而无法精确表示奇数整数,因此将其舍入为z,并添加x得出0.0.

x + y, with opposite signs, is inside the range and exactly representable. Adding z to the result gets 1.0, the real number result of the addition. On the other hand, y + z has equal signs, making the magnitude too large for odd integers to be exactly representable, so it rounds to z, and adding x results in 0.0.

这篇关于注意事项浮点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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