Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is (1/2)*x different from 0.5*x? [duplicate]

Tags:

c++

c

This behaves as wanted:

double t = r[1][0] * .5;

But this doesn't:

double t = ((1/2)*r[1][0]);

r is a 2-D Vector.

Just thought of a possibility. Is it because (1/2) is considered an int and (1/2) == 0?

like image 370
Roger Lam Avatar asked Mar 19 '12 03:03

Roger Lam


2 Answers

Is it because (1/2) is considered an int and (1/2) == 0?

Yes, both of those literals are of type int, therefore the result will be of type int, and that result is 0.

Instead, make one of those literals a float or double and you'll end up with the floating point result of 0.5, ie:

double t = ((1.0/2)*r[1][0]);

Because 1.0 is of type double, the int 2 will be promoted to a double and the result will be a double.

like image 81
AusCBloke Avatar answered Oct 12 '22 10:10

AusCBloke


Write this instead:

  double t = ((1/2.0)*r[1][0]);

1 / 2 is an integer division and the result is 0.

1 / 2.0 is a floating point division (with double values after the usual arithmetic conversions) and its result is 0.5.

like image 28
ouah Avatar answered Oct 12 '22 09:10

ouah