Skip to content

Instantly share code, notes, and snippets.

@jenetics
Last active September 26, 2019 17:50
Show Gist options
  • Save jenetics/3f581cf8f2c882f0b34d4c85f7d19d6a to your computer and use it in GitHub Desktop.
Save jenetics/3f581cf8f2c882f0b34d4c85f7d19d6a to your computer and use it in GitHub Desktop.
Polynomial codec
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