Last active
September 26, 2019 17:50
-
-
Save jenetics/3f581cf8f2c882f0b34d4c85f7d19d6a to your computer and use it in GitHub Desktop.
Polynomial codec
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
final class Polynomial { | |
private final double[] a; | |
Polynomial(final double... a) { | |
this.a = a.clone(); | |
} | |
// Uses Horner's Method to evaluate the polynomial. | |
double apply(final double x) { | |
double result = a[a.length - 1]; | |
for (int i = a.length - 2; i >= 0; i--) { | |
result = x*result + a[i]; | |
} | |
return result; | |
} | |
} | |
Codec<Polynomial, DoubleGene> codec(final int degree) { | |
return Codec.of( | |
Genotype.of(DoubleChromosome.of( | |
DoubleRange.of(-100, 100), | |
degree + 1) | |
), | |
gt -> new Polynomial( | |
gt.getChromosome() | |
.as(DoubleChromosome.class) | |
.toArray() | |
) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment