Ankit Anand
Ankit Anand

Reputation: 31

Large number of operations on double data type producing zero as result

I have a program which multiplies a probability over 500 times, but when I am doing so the output is zero. Should I use some other data type? Please help. Here is the code I am using:

double d = 1/80000d;
    for (int i = 0; i < 500; i++) {
        d *= d;
    }
    System.out.println(d);

Upvotes: 1

Views: 92

Answers (3)

Simon Byrne
Simon Byrne

Reputation: 7874

When working with probabilities, you can avoid these sort of numerical issues by working instead with logarithms, so that you can work additively. Something like

double d = 1/80000d;
double ld = Math.log(d)
for (int i = 0; i < 500; i++) {
    ld += ld;
}
System.out.println(ld);

Upvotes: 1

Marcelo Cuadrado
Marcelo Cuadrado

Reputation: 82

Naturally, if you have two numbers less than 1, and repeated the multiply times sooner or later will be small enough to not be able resepresented in Double, Extended, or any floating arithmetic it done in the future. ;)

What your turn is the aproximation that has been stored in the type. ZERO is one of the special constants of IEEE 754 format.

I do not know JAVA, but exist the type Extended in other languages.

Upvotes: 0

Eran
Eran

Reputation: 393936

The output is zero because double has a limited percision, and if you multiply a number lower than 1 by itself enough times, you'll get a result too small to be distinguished from 0.

If you print d after each iteration, you'll see that it becomes 0 quite fast :

1.5625E-10
2.4414062500000002E-20
5.960464477539064E-40
3.552713678800502E-79
1.2621774483536196E-157
1.593091911E-314
0.0

Upvotes: 2

Related Questions