2

Why does my code only go up to 2.4 for the x value as the output when I enter 0.1 as the step size? If I enter a value like .01 or .001 it goes up to 2.5.

#include <iostream>
#include <iomanip>
using namespace std; 
int main() {
    double step; 
    double x0 = 1.0; 
    double y0 = 1.0; 
    double diffY; 
    std::cout << std::fixed;
    std::cout << std::setprecision(2);
    cout << "Enter step value: ";
    cin >> step; 
    while (x0 <= 2.5 ) {

        diffY = x0 + ((3*y0) / x0);
        cout << x0 << "    " << y0 << "\n"; 
        x0+=step;
        y0+=step*(diffY);
    }

    return 0; //initially defined the main function to return an int
} 

Thanks!

  • You should loop using integer-based limits, and inside the loop, scale the values down. Otherwise your loop may run a differing number of times depending on compiler, compiler options, etc. – PaulMcKenzie Oct 11 '16 at 01:10

1 Answers1

0

Good old fashion floating point number errors, print out to a high precision your x0, you will get this:

1.1000000000000001
1.2000000000000002
...
2.4000000000000012
2.5000000000000013

Note how on your last past, you will increment past 2.5 therefore will not execute your last loop. This is because floating point numbers are binary (base 2) not decimal (base 10) so they cant represent every number exactly. This includes 0.1.

You should always use an epsilon when comparing floating point numbers:

float eps = step/100; // Only an example.
while (x0 <= 2.5 + eps ) {
    ...

For more info, read this. If you want to play, here is a live example.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
  • *"This is because floating point numbers are binary (base 2) not decimal (base 10) so they cant represent every number exactly."* That holds for any integer base (given finitely many digits). – Baum mit Augen Oct 11 '16 at 00:48
  • I suggest not looping with floating point loop counters whatsoever. By hook or by crook, get those loop constraint values to be integer. – PaulMcKenzie Oct 11 '16 at 01:11