Rounding error

Started by
3 comments, last by Ezbez 18 years, 6 months ago
I seem to be having a rounding error in the following lines of code:

float speed;
speed = (rand() % 20)/10 + .4;
Speed seems to be either 0.4 or 1.4, never anything in between. I would geuss that this would be because of a rounding error, but I can't seem to think of why this would round it off! Anyone know whats happening, or is there a mistake somewhere else in my code? Also, whats the script to set off a block of code in a post?
Advertisement
The problem is that rand returns an integer and you only do integer arithmetic. Change it to

speed = (rand() % 20.0)/10.0 + .4;

This will force the compiler to use floating point arithmetic.

Oh and the command is
[-source-]
//code goes here
[-/source-]

Except without the '-'s
Quote:speed = (rand() % 20.0)/10.0 + .4;

The modulus operator only works on integer types.

@OP: To better understand the problem, think of expressions. An expression is an arrangement of variables, constants, function calls and operators that specify a computation. An expression evalulates to a value of a given type.

In your code, speed is a floating point variable. It is assigned the value of the expression to the right of the assignment. The expression is:
(rand() % 20)/10 + .4;

The part inside the parentheses is evaluated first. It evaluates to an integer value. Next, this integer value is divided by 10. Given that the 2 operands of the division (the divisor and the dividend) are of the same integer type, the operation (division) will be carried out producing a result of the same type - an integer. This means the division result is truncated - You lose precision.

To solve this, you need the division to be evaluated in floating point arithmetic, which happens if one of the 2 operands is a float. So you make 10 a float:
(rand() % 20)/10.0f + .4;

One final thing. ".4" is a double precision floating point constant. When the addition operation is carried, the expression on the left of the '+' operator is of type float, but that to the right is of type 'double'. The value of the left expression will be promoted to the double type, and the addition will produce a result of type double. Then the assignment puts this double precision value into a floating point variable - which means loss of precision can occur. Typically, the compiler will issue a warning at this. To fix this, append an 'f', designating a floating point constant, to 0.4:
(rand() % 20)/10.0f + .4f;

Oh yeah...but you could use fmod(not the sound lib):

speed = (fmod( rand(), 20.0 ) / 10.0) + .4
Thanks for the help! That helped me understand whats going one alot better.(and tells me what all those random 'f's where at the end of numbers!)

Oh, and thanks for telling me how to show source codes.

This topic is closed to new replies.

Advertisement