innoave / genevo

Execute genetic algorithm (GA) simulations in a customizable and extensible way.
Other
173 stars 27 forks source link

How to use `f32` / `f64` as fitness scores? #18

Open wbrickner opened 3 years ago

wbrickner commented 3 years ago

Hello,

I am currently stuck using a janky float discretization technique because I can't use floats directly.

Is there a better workaround? Is there some truly compelling reason we cannot implement the Fitness trait for floats internally like is done for the signed and unsigned integers?

Thank you.

haraldmaida commented 2 years ago

The evaluation functions must order the fitness score. The Ord trait is not implemented for floats. That's the reason why the Fitness trait can not be implemented for floats. Maybe someone has an idea how to implement the comparison of Fitness values using the PartialOrd trait only. Specifically what to do when partial_cmp returns None.

ravicious commented 2 years ago

I enabled the total_cmp nightly feature and then wrote my own wrapper over f64 that implements Ord using total_cmp.

Here's how it looks like: https://github.com/ravicious/collage/blob/808fb238da24415b72371bded32d49994f2b611a/image-processor/src/algorithm.rs#L22-L64

Unfortunately it's not something one can copy and paste, as I also had to flip the order. By default genevo treats higher fitness as better, but the cost function of the algorithm I was implementing treats lower fitness as better with zero being the best possible fitness. But you should be able to just remove the match on self.0.total_cmp(&other.0) (line 47).

If you're sure that your cost function never returns NAN, I think you should be able to YOLO it and create a wrapper implementing Ord which panics if partial_cmp returns None. This happens only when you attempt to compare NAN, but I might be wrong on this. total_cmp on the other hand orders NAN before/after infinity values.