舍入错误? [英] Rounding Errors?

查看:141
本文介绍了舍入错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的课程中,我被告知:

In my course, I am told:


连续值大约在内存中表示,因此使用浮点数计算涉及舍入错误。这些是位模式的微小差异;因此,如果 e f e == f 是不安全的c>是花车。

Continuous values are represented approximately in memory, and therefore computing with floats involves rounding errors. These are tiny discrepancies in bit patterns; thus the test e==f is unsafe if e and f are floats.

参考Java。

这是真的吗?我已经使用了与 double float s的比较语句,并且从未遇到过舍入问题。我从未在教科书中读过类似的东西。当然虚拟机会解释这个吗?

Is this true? I've used comparison statements with doubles and floats and have never had rounding issues. Never have I read in a textbook something similar. Surely the virtual machine accounts for this?

推荐答案

这是真的。

浮点值在内存中以有限位数表示的固有限制。

It is an inherent limitation of how floating point values are represented in memory in a finite number of bits.

例如,此程序打印false:

This program, for instance, prints "false":

public class Main {
  public static void main(String[] args) {
    double a = 0.7;
    double b = 0.9;
    double x = a + 0.1;
    double y = b - 0.1;
    System.out.println(x == y);
  }
}

而不是与'=='进行精确比较决定某种程度的精确度,并询问这些数字是否足够接近:

Instead of exact comparison with '==' you usually decide on some level of precision and ask if the numbers are "close enough":

System.out.println(Math.abs(x - y) < 0.0001);

这篇关于舍入错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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