Repository navigation
Expand file tree
/
Copy pathexample_maximize_cylinder_volume.py
More file actions
64 lines (50 loc) · 1.73 KB
/
Copy pathexample_maximize_cylinder_volume.py
File metadata and controls
64 lines (50 loc) · 1.73 KB
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
import habitat
import random
import math
#A example program that maximizes the volume of a 3d cylinder, given a
#maximum surface area.
#Generate a initial untested solution
def init():
genome = []
for i in range(2):
genome.append(random.uniform(0, 2.0))
return genome
#mutate a solution
def mutate(genome):
rtn = genome.copy()
if random.getrandbits(1) == 1:
if random.getrandbits(1) == 1:
rtn[0] = random.uniform(0, 1.0)
if random.getrandbits(1) == 1:
rtn[1] = random.uniform(0, 1.0)
elif random.getrandbits(1) == 1:
rtn[0] += random.uniform(-0.01, 0.01)
rtn[1] += random.uniform(-0.01, 0.01)
else:
changeradius = random.uniform(-0.001, 0.001)
changeheight = -changeradius * (rtn[1]/rtn[0]) + random.uniform(-0.0001, 0.0001)
rtn[0] = rtn[0] + changeradius;
rtn[1] = rtn[1] + changeheight;
return rtn
#print a solution
def output(genome):
print("radius and height: "+ str(genome))
print("score: " + str(evaluate(genome)))
print("the ratio between radius and height is: " + str(genome[1]/genome[0]))
print("---------")
#evaluate a solution to compare it to other solutions
def evaluate(genome):
if calculate_surface_area(genome) > math.pi:
return 0
else:
return calculate_volume(genome)
#genome[0] is the radius, genome[1] is the height
def calculate_surface_area(genome):
top_and_bottom_area = 2.0*(math.pi*genome[0]*genome[0])
side_area = (2.0*math.pi*genome[0])*genome[1]
return top_and_bottom_area + side_area
#genome[0] is the radius, genome[1] is the height
def calculate_volume(genome):
return math.pi*genome[0]*genome[0]*genome[1]
#run the algorithm
habitat.run(init, mutate, output, evaluate)