简体   繁体   English

如何处理 java 中的下溢?

[英]How to deal with underflow in java?

Here's the issue这是问题

double a = 1.0665901062490447E-18;
double b = 1.0;
double c = a+b; // this is 1.0

I need that summed value.我需要那个总和值。 What do I do about it?我该怎么办?

As I mentioned in my comment , 1.0665901062490447E-18 is a very small value.正如我在评论中提到的, 1.0665901062490447E-18是一个非常小的值。 If you need that much precision, you should be using BigDecimal .如果你需要这么高的精度,你应该使用BigDecimal Something like,就像是,

double a = 1.0665901062490447E-18, b = 1.0;
System.out.println(BigDecimal.valueOf(a).add(BigDecimal.valueOf(b)).toPlainString());

Which outputs哪个输出

1.0000000000000000010665901062490447

Note that there is a predefined constant BigDecimal.ONE - so the above could also be written请注意,有一个预定义的常量BigDecimal.ONE - 所以上面也可以写成

System.out.println(BigDecimal.valueOf(a).add(BigDecimal.ONE).toPlainString());

There are limits to what primitive types can do in almost any language.几乎所有语言中的基本类型都存在限制。 In this case, the double type I believe is bound by IEEE-754 .在这种情况下,我认为double类型受IEEE-754约束。 In order to handle these class of problems Arbitrary Precision Libraries have been created for many languages.为了处理这些 class 问题,已经为多种语言创建了任意精度库

The classic "What Every Computer Scientist Should Know About Floating Point Arithmetic" is required reading for all uses of floating point data types.对于浮点数据类型的所有用途,都需要阅读经典的“每个计算机科学家应该知道的关于浮点运算的知识”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM