0

Basically i have this loop giving me answers for a formula:

for(int i = 1; i <= 50; i = i + 1) {
    double y = ((-1000/(i + 29)) + (100/3));
    System.out.println(i + " | "+ y);
}

This loop should give me the values of y for values of i (aka. x) 1->50.

This is what it outputs:

1 | 0.0
2 | 1.0
3 | 2.0
4 | 3.0
5 | 4.0
6 | 5.0
7 | 6.0
etc until 50

It shouldn't end in .0 every time.

When i cast 'i' to be double:

for(int i = 1; i <= 50; i = i + 1) {
    double y = ((-1000/((double)i + 29)) + (100/3));
    System.out.println(i + " | "+ y);
}

It outputs:

1 | -0.3333333333333357
2 | 0.741935483870968
3 | 1.75
4 | 2.6969696969696955
5 | 3.5882352941176485
6 | 4.428571428571427
7 | 5.222222222222221
etc until 50

However. Just putting the function into a graphing software (I tried wolfram alpha, desmos, symbolab and calculating y by hand). I got different results than my Java loop.

Here is what my program should output (to 3dp)

1 | 0
2 | 1.083
3 | 2.083
4 | 3.030
5 | 3.922
6 | 4.762
7 | 5.556
etc. i dont want to write these all out

What have i done wrong here?

I hope to hear from someone.

Thanks,

-WDK

  • 1
    Maybe another duplicate: https://stackoverflow.com/questions/4685450/int-division-why-is-the-result-of-1-3-0 – Lino Mar 12 '19 at 11:54
  • 1
    Casting `i` to `double` isn't sufficient, you also need to handle the fact that `100/3` is `33`, not `33.3333333333`, since both of those literals are integer literals. Then there's the whole issue of the precision of `double`, [more here](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). – T.J. Crowder Mar 12 '19 at 11:54

1 Answers1

0

switch to:

    for(int i = 1; i <= 50; i = i + 1) {
        double y = ((-1000./(i + 29)) + ((100.)/3));
        System.out.println(i + " | "+ y);
    }
ZhenyaM
  • 676
  • 1
  • 5
  • 15