分割和乘法交替过程中的Java精度 [英] Java precision during division and multiplication alterneting process

查看:267
本文介绍了分割和乘法交替过程中的Java精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何解决Java Rounding双重问题

请帮助,
我编程一些Java中的计算器。我使用双重类型。双数位在小数点后15位。我有以下问题:

Please Help, I programm some calculator in Java. I use double type. Double has 15 digits after the decimal point. I have problem with the following:

1/3 * 3 = 0.9999999999999999

1/3 * 3 = 0.9999999999999999

我需要1/3 * 3 = 1

I need 1/3 * 3 = 1

我如何解决这个问题?
我保持结果为Double。与其他数学运算相同的问题,例如

How can I solve this problem? I keep result in Double. The same problem I have with other mathematical operations, for example

sqrt(6)= 2.449489742783,接下来我平方的结果,我得到:5.999999999999999

sqrt(6) = 2.449489742783, and next I square the result and I get: 5.999999999999999

推荐答案

您正在处理浮点运算的固有局限性。

You're dealing with inherent limitations of floating-point arithmetic.

  • Read the paper What Every Computer Scientist Should Know About Floating-Point Arithmetic.
  • For equality-checking, you should be using something like abs(x-y) < epsilon rather than x == y
  • For display purposes, you should round to the nearest decimal place that you actually care about.

这篇关于分割和乘法交替过程中的Java精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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