question about float division
Hi,
I'm trying to calculate a fitness value for a genetic algorithm like this:
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:
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
Anthony
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

Anthony
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.
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.
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!


