Why doesn't Double.infinite return true for infinite fractions?

Double.isInfinite(1.0 / 0.0);

returns true.

Double.isInfinite(1.0 / 3.0);

but this is not so, and as far as I know, it will be an infinite number, since this returns 0.33333_ to infinity.

why?

+4
source share
3 answers

Double.isInfinitedoes not return true if the value is infinitely long; it returns true if the value itself is infinite (positive or negative).

In addition, 1.0 / 3.0 is infinitely long at base 10, but not at other bases like base 3.

+11
source

double . 1.0/3.0 "1/3", , double . 18 000 000 000 000 000 double , 6004799503160661/18014398509481984, 1.0/3.0 . " " , , double "" ; 54 .

+2

The IEEE-754 (+/- infinity) have two values, defined as infinity. Since double is a floating point, it follows these rules. However, if you were to use an arbitrary type of precision (e.g. BigDecimal ), you could implement such a test - for example,

public static void main(String[] args) {
    BigDecimal ONE = BigDecimal.ONE;
    BigDecimal THREE = new BigDecimal("3");
    BigDecimal THIRD = ONE.divide(THREE);
    System.out.println(THIRD);
}

Throws an exception

An exception in the stream "main" java.lang.ArithmeticException: Non-limiting decimal extension; no exact representable decimal result.

+1
source

Source: https://habr.com/ru/post/1540894/


All Articles