Last active
January 12, 2016 17:08
-
-
Save cesare/85651bf94691235cc116 to your computer and use it in GitHub Desktop.
5.2 polynomials
This file contains 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
defmodule Chapter5 do | |
def polynomial2(as, x) do | |
Stream.iterate(1, &(&1 * x)) | |
|> Enum.zip(as) | |
|> Enum.map(fn {x, a} -> x * a end) | |
|> Enum.sum | |
end | |
def polynomial3(as, x) do | |
Enum.reverse(as) |> Enum.reduce(&(&2 * x + &1)) | |
end | |
end |
This file contains 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
polynomial1 :: [Double] -> Double -> Double | |
polynomial1 as x = poly as x 0 | |
where | |
poly [] x i = 0 | |
poly (b:bs) x i = b * (x**i) + (poly bs x (i + 1)) | |
polynomial2 :: [Double] -> Double -> Double | |
polynomial2 as x = sum $ zipWith (*) as xs | |
where | |
xs = 1:zipWith (*) xs [x, x..] | |
polynomial3 :: [Double] -> Double -> Double | |
polynomial3 as x = foldr1 (\a p -> x * p + a) as |
This file contains 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
# as: [a0, a1, a2, a3, ..., an] | |
def polynomial1(as, x, i = 0) | |
if as.empty? | |
0 | |
else | |
as.first * (x**i) + polynomial1(as.drop(1), x, i + 1) | |
end | |
end | |
def polynomial2(as, x) | |
as.reduce([0, 1]) {|(t, xe), a| [t + a * xe, xe * x] }.first | |
end | |
def polynomial3(as, x) | |
as.reverse.reduce {|p, a| p * x + a } | |
end | |
def polynomial_all(as, x) | |
(1..3).map do |n| | |
send :"polynomial#{n}", as, x | |
end | |
end | |
examples = [ | |
[[4,3,2,1], 5], | |
[[1.2, 9.8, -7.3], 12.9] | |
] | |
examples.each do |(as, x)| | |
puts '=' * 80 | |
puts "as = #{as}, x = #{x}" | |
puts polynomial_all(as, x) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment