This repository was archived by the owner on Jan 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexercise25.rb
More file actions
76 lines (57 loc) · 1.55 KB
/
Copy pathexercise25.rb
File metadata and controls
76 lines (57 loc) · 1.55 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
65
66
67
68
69
70
71
72
73
74
75
76
require_relative 'exercise23.rb'
# Exercise 25
DEG = 0.0174532925 # rad in deg
class MonoExpressionNode
attr_reader :operator
attr_writer :operand
def initialize(op)
@operator = op
end
def evaluate
opr = @operand.evaluate
case @operator
when :sqrt
r = Math.sqrt(opr)
when :fact
r = Math.gamma(opr + 1)
when :squared
r = opr**2
when :sine
r = Math.sin(opr * DEG)
end
return r
end
end
left = ExpressionNode.new(:times)
left.left_operand = Literal.new(36)
left.right_operand = Literal.new(2)
right = ExpressionNode.new(:times)
right.left_operand = Literal.new(9)
right.right_operand = Literal.new(32)
main = ExpressionNode.new(:divide)
main.left_operand = left
main.right_operand = right
final = MonoExpressionNode.new(:sqrt)
final.operand = main
raise "Error" if final.evaluate != Math.sqrt((36*2.0)/(9*32))
fac1 = MonoExpressionNode.new(:fact)
fac1.operand = Literal.new(5)
sub = ExpressionNode.new(:minus)
sub.left_operand = Literal.new(5)
sub.right_operand = Literal.new(3)
fac2 = MonoExpressionNode.new(:fact)
fac2.operand = sub
fac3 = MonoExpressionNode.new(:fact)
fac3.operand = Literal.new(3)
right = ExpressionNode.new(:times)
right.left_operand = fac2
right.right_operand = fac3
main = ExpressionNode.new(:divide)
main.left_operand = fac1
main.right_operand = right
raise "Error" if main.evaluate != 120.0 / (2 * 6)
si = MonoExpressionNode.new(:sine)
si.operand = Literal.new(45)
main = MonoExpressionNode.new(:squared)
main.operand = si
raise "Error" if main.evaluate != (Math.sin(45*DEG))**2