Polynomial long division: Difference between revisions

→‎{{header|Ruby}}: reform of the display
(Updated D entry)
(→‎{{header|Ruby}}: reform of the display)
Line 1,464:
 
def degree(ary)
idx = ary.rindex {|x| x.(&:nonzero?})
idx.nil? ? -1idx : idx-1
end
 
Line 1,483:
g = [-3, 1, 0, 0]
q, r = polynomial_long_division(f, g)
puts "#{f} / #{g} => #{q} remainder #{r}"
p [f, g, q, r]
# => [[-42, 0, -12, 1], / [-3, 1, 0, 0], => [-27, -9, 1, 0, 0], remainder [-123, 0, 0, 0, 0]]
 
g = [-3, 1, 1, 0]
q, r = polynomial_long_division(f, g)
puts "#{f} / #{g} => #{q} remainder #{r}"
p [f, g, q, r]
# => [[-42, 0, -12, 1], / [-3, 1, 01, 0], => [-13, 1, 0, 0, 0], remainder [-81, 16, 0, 0, 0]]</lang>
 
Implementing the algorithms on the [[wp:Polynomial long division|wikipedia page]] -- uglier code but nicer user interface
Line 1,553:
g = [1, -3]
q, r = polynomial_division(f, g)
puts "#{f} / #{g} => #{q} remainder #{r}"
p [f, g, q, r]
# => [[1, -12, 0, -42], / [1, -3], => [1, -9, -27], remainder [-123]]
 
g = [1, 1, -3]
q, r = polynomial_division(f, g)
puts "#{f} / #{g} => #{q} remainder #{r}"
p [f, g, q, r]
# => [[1, -12, 0, -42], / [1, 1, -3], => [1, -13], remainder [16, -81]]</lang>
 
Best of both worlds: {{trans|Tcl}}
<lang ruby>def tcl_polynomial_divisionpolynomial_division(f, g)
if g.length == 0 or (g.length == 1 and g[0] == 0)
raise ArgumentError, "denominator is zero"
Line 1,568:
return [[0], f] if f.length < g.length
q, n = [], f.dup
while n.length >= dg.length
n, d = f.dup, g
q << Float(n[0]) / dg[0]
while n.length >= d.length
n[0, g.length].zip(g).each_with_index do |pair, i|
q << Float(n[0]) / d[0]
n[i] = pair[0,] d.length- q[-1].zip(d).each_with_index do* |pair, i|[1]
n[i] = Float(pair[0]) - q[-1] * pair[1]
end
n.shift
Line 1,585 ⟶ 1,584:
g = [1, -3]
q, r = polynomial_division(f, g)
puts "#{f} / #{g} => #{q} remainder #{r}"
p [f, g, q, r]
# => [[1, -12, 0, -42], / [1, -3], => [1.0, -9.0, -27.0], remainder [-123].0]
 
g = [1, 1, -3]
q, r = polynomial_division(f, g)
puts "#{f} / #{g} => #{q} remainder #{r}"
p [f, g, q, r]
# => [[1, -12, 0, -42], / [1, 1, -3], => [1.0, -13.0], remainder [16.0, -81].0]</lang>
 
=={{header|Slate}}==
Anonymous user