question about float division

Member
Posts: 61
Joined: 2007.01
Post: #1
Hi,

I'm trying to calculate a fitness value for a genetic algorithm like this:
Code:
mFitness = 1.0f / 1.0f + (badMoves + totalDist);

mFitness, badMoves and totalDist are all floats because I want the precision.

However, badMoves and totalDist will hold "whole" numbers (if that's the correct word to use), as in they'll never be 10.01 etc.

So I sample run of the algorithm would give results like:

mFitness = 1.0f / 1.0f + (2.0f + 0.0f)

but the output will be 3 instead of 0.3333.

Is there way to set the precision?

What's really puzzling me is that if I try to calculate the ratio of bad moves to the total moves (another float), the result will often be values to 2 decimal places.

And the code for that is simply:

Quote:float moveRatio = badMoves / totalMoves;

At this point I don't know if it's something I'm doing wrong or just a compiler issue.

I'm using Xcode and I have zerolink turned off if any of that matters.

Thanks for any help Smile
Anthony
Quote this message in a reply
Member
Posts: 63
Joined: 2005.12
Post: #2
Looks like it's just an order-of-operations problem. The code you have now equates to:

mFitness = (1.0f / 1.0f)+ (badMoves + totalDist);

Which is the same as:

mFitness = 1.0f + badMoves + totalDist;

Which is why, in your example, you get an answer of '3'.

Changing the code to:

mFitness = 1.0f / (1.0f + badMoves + totalDist);

Should resolve the problem.
Quote this message in a reply
Member
Posts: 61
Joined: 2007.01
Post: #3
Blush

I can't believe I didn't see that, thanks a million _jyk_ Smile
Quote this message in a reply
Sage
Posts: 1,403
Joined: 2005.07
Post: #4
anthony Wrote:mFitness, badMoves and totalDist are all floats because I want the precision.
doubles are likely more precise than floats.

anthony Wrote:However, badMoves and totalDist will hold "whole" numbers (if that's the correct word to use), as in they'll never be 10.01 etc.
They're integers.

Sir, e^iπ + 1 = 0, hence God exists; reply!
Quote this message in a reply
Post Reply