-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalgebra
executable file
·88 lines (76 loc) · 1.65 KB
/
algebra
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
#!/usr/bin/env ruby
class Solver
attr_accessor :n, :guess, :answer, :verbose
def initialize equation, accuracy, verbose
@n = 0
@precision = 1
@accuracy = accuracy
@equation = equation
@answer = evaluate @equation.split("=")[1]
@verbose = verbose
end
def evaluate expr
expr.gsub! /x/i, @n.to_s
expr.gsub!(/(sqrt|log)/i) { "Math::#{$1.downcase}" }
expr.gsub!(/(pi|e)/i) { "Math::#{$1.upcase}" }
eval(expr).round @accuracy
end
def try_equation
equality = @equation.split("=")[0].gsub /x/i, @n.to_s
puts "Trying #{equality} = #{@answer}".squeeze " " if @verbose
@guess = evaluate equality
if @guess > @answer
subtract_from_n
add_precision
end
@guess == @answer
end
def add_to_n
case @n
when Fixnum
@n += @precision
when Float
num_to_add = "0.#{'0' * (@precision - 1)}1".to_f
@n = ("%.#{@precision}f" % (@n + num_to_add)).to_f
end
end
def subtract_from_n
case @n
when Fixnum
@n -= @precision
when Float
num_to_subtract = "0.#{'0' * (@precision - 1)}1".to_f
@n = ("%.#{@precision}f" % (@n - num_to_subtract)).to_f
end
end
def add_precision
case @n
when Fixnum
@n = "#{n}.1".to_f
# @n = @n.to_f
when Float
num_to_add = "0.#{'0' * @precision}1".to_f
@precision += 1
@n = ("%.#{@precision}f" % (@n + num_to_add)).to_f
end
end
end
until ARGV.empty?
case ARGV[0]
when "-v"
verbose = true
ARGV.shift
when "-a", "-p"
ARGV.shift
accuracy = ARGV.shift.to_i
else
equation = ARGV.shift
end
end
s = Solver.new equation, accuracy ||= 2, verbose ||= false
result = s.try_equation
until result
s.add_to_n unless s.guess > s.answer
result = s.try_equation
end
puts "x = #{s.n}"