-4

For the following simple while loop, once in every 5 runs, I get a list of wrong values for x, as if the values jump suddenly:

package test;
public class test_old {

public static void main(String [] args) {
    double r0 = 0.1;
    double r = 10; 
    double k = 0.05; 
    double x = 0; 
    double Tt = 0;
    double T = 0;
    while (Tt<=30) {
        double xi = Math.random();
        T = Math.log(1/xi)/(k*x + r0 + r);
        Tt = Tt + T;
        x = x + 1;
        System.out.println(x);
    }   
}
}

Instead of getting 1.0, 2.0, 3.0, .. etc (usually around 4 values until Tt is bigger than 30), I sometimes get a list of x values that seems to go on for ever starting at for example 89462.0, or 19945.0. The list of x values is correctly incremented by 1, but it never stops. I am a beginner using Eclipse. Thank you everyone for your time!

Sarath Chandra
  • 1,850
  • 19
  • 40
katma136
  • 1
  • 1

1 Answers1

0

Math.random () give values 0.0<=v<1.0 so if random gives you something like

v=0.99999999, log(1/v)=0.00000000001...

continue the calculation Tt=0+0.00000000001 will take like forever to be >30 just to test replace

 double xi = Math.random();

by

 double xi = 0.999999999999;

and run again I don't know why this happen but it seems that the random gives you values like 0.9999...

so to avoid this you have to insure that random gives you smaller value you can use this post Math.random() explained

Community
  • 1
  • 1
Billydan
  • 395
  • 1
  • 7
  • 25