-
Notifications
You must be signed in to change notification settings - Fork 1
/
PiGene.java
103 lines (89 loc) · 1.91 KB
/
PiGene.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import java.util.*;
/**
* A gene for solving the Pi problem which has a Double value
* between 3 and 4.
*/
public class PiGene implements Gene<Double> {
protected Double value;
protected double fitness;
protected Random rand;
public PiGene() {
rand = new Random();
}
/**
* Set the value of the gene to a specified value.
*
* @param value the value to be set
*/
public void setValue(Double value) {
this.value = value;
}
/**
* Set the value of the gene to a random double between 3 and 4.
*
* @return the randomized value
*/
public Double setRandomValue() {
value = new Double(3 + rand.nextDouble());
return value;
}
/**
* Get the value of the gene.
*
* @return the value of the gene.
*/
public Double getValue() {
return value;
}
/**
* Calculate and set the fitness of the gene.
*
* @return the calculated fitness
*/
public double setFitness() {
fitness = Math.abs(Math.PI-value);
return fitness;
}
/**
* Get the fitness of the gene.
*
* @return the fitness of the gene
*/
public double getFitness() {
return fitness;
}
/**
* Combine this gene's value with another one.
*
* @param value2 the value of the second gene
* @return the combined value
*/
public Double combineValues(Double value2) {
double recombo1 = 0.5 * value + 0.5 * value2;
double recombo2 = 1.5 * value - 0.5 * value2;
double recombo3 = 1.5 * value2 - 0.5 * value;
return new Double(best(recombo1, recombo2, recombo3));
}
/* Find the best offspring. */
private double best(double a, double b, double c) {
double fA = Math.abs(Math.PI-a);
double fB = Math.abs(Math.PI-b);
double fC = Math.abs(Math.PI-c);
if (fA < fB && fA < fC) {
return a;
}
else if (fB < fC) {
return b;
}
return c;
}
/**
* Mutate this gene's value
*
* @return the mutated value
*/
public Double mutateValue() {
/* Not supported for Pi gene*/
return value;
}
}