如何在 Java 中实现无穷大?

2022-01-14 00:00:00 integer long-integer double java infinity

Java 是否有任何东西可以表示每种数值数据类型的无穷大?它是如何实现的,以便我可以用它进行数学运算?

Does Java have anything to represent infinity for every numerical data type? How is it implemented such that I can do mathematical operations with it?

例如

int myInf = infinity; //However it is done
myInf + 5; //returns infinity
myInf*(-1); //returns negative infinity

我尝试过使用非常大的数字,但我想要一个合适的简单解决方案.

I have tried using very large numbers, but I want a proper, easy solution.

推荐答案

double 支持 Infinity

double supports Infinity

double inf = Double.POSITIVE_INFINITY;
System.out.println(inf + 5);
System.out.println(inf - inf); // same as Double.NaN
System.out.println(inf * -1); // same as Double.NEGATIVE_INFINITY

打印

Infinity
NaN
-Infinity

注意:Infinity - Infinity 不是数字.

相关文章