Re: Weirdness: (-0.666667 + 0.333333)

From: Corne' Cornelius (cornec_at_nospam-for-noreason.uy)
Date: 05/06/04

  • Next message: Gert Van den Eynde: "Re: Weirdness: (-0.666667 + 0.333333)"
    Date: Thu, 06 May 2004 09:17:40 +0200
    
    

    i should've made it more clear what i actually want to do.

    I'm not really trying to compare 2 double which could be in accurate
    becuase of rounding errors.

    I'm writing a program that draws graphs on a cartesian plane, so in
    order to go on the x-axis from say -2, to +2, in 20 intervals, i need
    one of these point to be zero or very close to it.

    how could i make sure i don't get rounding problems ?

    Corne' Cornelius wrote:
    > Hi,
    >
    > I'm experiencing some weirdness in a program, when subtracting 2
    > (double)'s which should result in 0, but instead it returns
    > -1.11022e-16. It looks to me that changing the double x_step decleration
    > to unsigned type, might help, but the compiler complains when i try that.
    >
    > Any ideas ?
    >
    > #include <iostream>
    > using namespace std;
    >
    > int main(int argc, char *argv[]) {
    >
    > double x1 = -1;
    > double x2 = 1;
    > double nx = 6;
    > int pos = 0;
    > double x = 0.0;
    > double x_step = 0.0;
    >
    > x_step = (x2 - x1) / nx;
    >
    > x = x1;
    > for (pos = 0; pos < nx; pos++) {
    > cout << x << " +\t" << x_step << " =\t " << (x +
    > x_step) << endl;
    > x = x + x_step;
    > }
    >
    > return 0;
    > }
    >
    >
    > Output:
    >
    > -1 + 0.333333 = -0.666667
    > -0.666667 + 0.333333 = -0.333333
    > -0.333333 + 0.333333 = -1.11022e-16
    > -1.11022e-16 + 0.333333 = 0.333333
    > 0.333333 + 0.333333 = 0.666667
    > 0.666667 + 0.333333 = 1
    >


  • Next message: Gert Van den Eynde: "Re: Weirdness: (-0.666667 + 0.333333)"

    Relevant Pages

    • Re: Weirdness: (-0.666667 + 0.333333)
      ... > becuase of rounding errors. ... > I'm writing a program that draws graphs on a cartesian plane, ... The only thing you can do is to compare your value of x to zero ...
      (comp.lang.cpp)
    • Re: addition of 0.7 and 0.1 is not 0.8 CDbl / CStr vbs problem
      ... values are stored there will be very small rounding errors. ... Comparing floating point values should be done using a tolerance:- ... Most newbies find this situation shocking yet it's pratically as old as ... the situation using CDbl) than to compare with "almost near ...
      (microsoft.public.scripting.vbscript)
    • Re: Weirdness: (-0.666667 + 0.333333)
      ... In message, Corne' Cornelius ... >I'm not really trying to compare 2 double which could be in accurate ... You can often improve matters by using an integer loop counter: ... It doesn't get rid of the rounding errors, but it does ensure that they ...
      (comp.lang.cpp)