Can anyone tell me why the calculations on lines 9 and 11, which seem to be identical, produce two different outputs. I know the difference isn\'t that great, but I am using the
To keep your code stable so your OpenGL output behaves nicely, you should probably do all (or as much as possible) of your calculations using doubles so that truncation effects do not accumulate and at the end (where I assume you need an integer pixel number) either always round to generate an integer value or truncate, but not mix the two.
This is an instance of GCC's most common non bug
That's how float behaves. Because of rounding error you don't get an exact result. It is extremely close to 410 for example 409.99999923
. However, if you print it as a float, by default c++ round to 6 figures and thus gives you 410
. In the second time, you assign it to integer. In this case, c++ doesn't perform a rounding but a truncation. This is why 409.
The real answer is somewhere around 409.9999999
.
This is outputting a double
and rounding to 410
because the math is all inlined:
std::cout << 400+(sin((90*3.14159)/180)*10) << std::endl;
since ypos
is declared as an int
, the double value is being truncated to 409
(which is the defined behavior when casting from double
to int
):
ypos=ypos+(sin((90*3.14159)/180)*10);
/// Output: 409.
std::cout << ypos << std::endl;
Note that you could also increase the accuracy by using a better constant for PI:
const double PI = 3.141592653589793238463;
std::cout << 400+(sin((90*PI)/180)*10) << std::endl;
but I would still store the result in a double
instead of an int
to avoid truncating. If you need an integer result then I would round first:
ypos += round(sin((90*PI)/180)*10);
This is outputting a floating point number
std::cout << 400+(sin((90*3.14159)/180)*10) << std::endl;
But this is outputting an integer, so will have been truncated
std::cout << ypos << std::endl;