(float)direction*PI/180.0f
uses double
arithmetic. PI
is a double
literal, since it has no f
suffix. The other two operands ((float)direction
and 180.0f
) are float
s, yes, but they just get promoted to double
(and the conversion is exact in IEEE floating point). Note that the (float)
is only applying to direction
due to operator precedence. For test2
, you pass the resulting double
directly to sin
, and sin
returns exactly 1
. For test
, you cast the double
down to float
in the assignment to theta
first, and then you cast it back up to double
for the call to sin
(note that you are calling C's double sin(double)
, not C++'s float std::sin(float)
). Through the casts, theta
loses a little of its value to rounding. sin
then gives a value correspondingly a little less than 1
, which then rounds all the way to 0
when cast to int
. If you had called std::sin
, then you would have gotten 1
, since std::sin
would round that slightly less than 1
double
into a float
, which would give 1
(unlike truncating to int
).
Printing floating point values to std::cout
like this is not useful for debugging floating point, since the values get rounded. I like using std::hexfloat
, which shows the real binary values (converted to hexadecimal), not decimal lies. I've also gotten rid of PI
and turned the C-style casts into functional-style casts to show what's going on more clearly. I've turned test
and test2
into double
s (sin
's return type) so we can take a real look at them.
int main() {
int direction = 90;
float theta = float(direction)*3.14159265/180.0f;
double test1 = sin(theta);
double test2 = sin(float(direction)*3.14159265/180.0f);
std::cout << std::hexfloat;
std::cout << theta << " " << float(direction)*3.14159265/180.0f << "\n";
std::cout << test1 << " " << test2 << "\n";
}
Godbolt
It gives
0x1.921fb6p+0 0x1.921fb53c8d4fp+0
0x1.ffffffffffff7p-1 0x1p+0
Which neatly shows us that the value we're using in test2
has more digits than theta
, since it's a double
but float theta
. You also see that test1
is almost 1
, but not quite.