Java的精度损失 [英] Java loss of precision

查看:176
本文介绍了Java的精度损失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与精度下降有关的问题

I have a problem concerned with losing of precision

我的任务是将数字打印为字符串

my task is to print numbers as strings

int exponent = ...
int[] Mantissas = { 1, 2, 5 };
double dataStep = java.lang.Math.pow(10.0, exponent) * Mantissas[mantissaIndex];
...
for (int i = 0; i < NSteps; i++)
                    steps[i] = firstStep + i * dataStep;
draw(steps);

例如0.2 * 7 = 1.4000000000000001; 0.0000014/10 = 1.3999999999999998E-7

for example, 0.2*7=1.4000000000000001; 0.0000014/10=1.3999999999999998E-7

如何解决这个问题?

UPD :主要问题是字符串输出格式.我不担心丢失约0.00000001的值. 现在,我将其解析为String.format(%f",value), 但我认为这不是一个好方法

UPD: The main problem is string output formating. i don't bother about losting of about 0.00000001 value. Now I solved it as String.format("%f", value), but I think it's not good approach

推荐答案

正如其他人所提到的,您必须使用 java.math.BigDecimal 而不是float/double.但是,这有其自身的一系列问题.

As mentioned by others you have to use java.math.BigDecimal instead of float/double. This however comes with its own set of problems.

例如,当您调用BigDecimal(double)时,您传入的值将扩展为其完整表示形式:

For instance when you call BigDecimal(double) the value you pass in will be expanded to its full representation:

BigDecimal oneTenth = new BigDecimal(0.1);
BigDecimal oneMillion = new BigDecimal(1000000);
oneTenth.multiply(oneMillion)
out> 100000.0000000000055511151231257827021181583404541015625000000

但是当您使用BigDecimal(String)构造函数时,表示的是eact值,您会得到

But when you use the BigDecimal(String) constructor the eact value is represented and you get

BigDecimal oneTenth = new BigDecimal("0.1");
BigDecimalr oneMillion = new BigDecimal(1000000);
oneTenth.multiply(oneMillion)
out> 100000.0

您可以在Joshua Bloch和Neal Gafter出色的 Java拼图游戏以及这篇内容丰富的文章.最后请注意,BigDecimal上的toString将以科学计数法打印,因此您必须正确地使用 toPlainString .

You can read more on BigDecimal's limitations in Joshua Bloch and Neal Gafter's splendid Java puzzlers book and in this informative article. Finally note that toString on BigDecimal's will print in scientific notation so you will properly have to use toPlainString instead.

这篇关于Java的精度损失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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