Last active
December 24, 2015 11:19
-
-
Save rklemme/6790261 to your computer and use it in GitHub Desktop.
Code examples about "prior knowledge"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/ruby | |
require 'benchmark' | |
def sin radians | |
h = Hash.new(Math.sin(radians)) | |
h[0.0] = 0 | |
h[90.0] = 1 | |
h[180.0] = 0 | |
h[270.0] = -1 | |
degrees = (radians / Math::PI * 180) % 360 # think in degrees for ease | |
h[degrees] | |
end | |
def sin2 x | |
rad = (x / Math::PI * 180) % 360 # think in degrees for ease | |
case rad | |
when 0; 0 | |
when 90; 1 | |
when 180; 0 | |
when 270; -1 | |
else Math.sin(x) | |
end | |
end | |
REPEAT = 1_000_000 | |
Benchmark.bmbm 20 do |x| | |
x.report "Math.sin(0)" do | |
REPEAT.times { Math.sin(0) } | |
end | |
x.report "Math.sin(0.0)" do | |
REPEAT.times { Math.sin(0.0) } | |
end | |
x.report "sin(0)" do | |
REPEAT.times { sin(0) } | |
end | |
x.report "sin(0.0)" do | |
REPEAT.times { sin(0.0) } | |
end | |
x.report "sin2(0)" do | |
REPEAT.times { sin2(0) } | |
end | |
x.report "sin2(0.0)" do | |
REPEAT.times { sin2(0.0) } | |
end | |
end | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
def fib1(n) | |
case n | |
when 0 then 0 | |
when 1 then 1 | |
else fib1(n-1) + fib1(n-2) | |
end | |
end | |
def fib2(n) | |
case n | |
when 0 then 0 | |
when 1 then 1 | |
else | |
f0 = 0 | |
f1 = 1 | |
for i in 2..n | |
f0, f1 = f1, f0 + f1 | |
end | |
f1 | |
end | |
end | |
fib3 = Hash.new do |h, n| | |
last = nil | |
for i in 2..n | |
h[i] = last = h[i - 1] + h[i - 2] | |
end | |
last | |
end.update(0 => 0, 1 => 1) | |
fib4 = Hash.new do |h, n| | |
last = nil | |
(h.m + 1).upto n do |i| | |
h[i] = last = h[i - 1] + h[i - 2] | |
end | |
h.m = n # we know n > h.m | |
last | |
end.update(0 => 0, 1 => 1) | |
class <<fib4 | |
attr_accessor :m | |
end | |
fib4.instance_variable_set '@m', 1 | |
10.times do |n| | |
f1 = fib1 n | |
f2 = fib2 n | |
f3 = fib3[n] | |
f4 = fib4[n] | |
printf "%10d %10d %10d %10d\n", f1, f2, f3, f4 unless f1 == f2 && f2 == f3 && f2 == f4 | |
end | |
REPEAT = 100_000 | |
Benchmark.bm 20 do |x| | |
x.report "fib1" do | |
REPEAT.times { fib1 10 } | |
end | |
x.report "fib2" do | |
REPEAT.times { fib2 10 } | |
end | |
x.report "fib3" do | |
REPEAT.times { fib3[10] } | |
end | |
x.report "fib4" do | |
REPEAT.times { fib4[10] } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment