Skip to content

Instantly share code, notes, and snippets.

@stephancom
Last active January 5, 2020 05:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephancom/f3b9a7871396cd5edf8a7f562ec324be to your computer and use it in GitHub Desktop.
Save stephancom/f3b9a7871396cd5edf8a7f562ec324be to your computer and use it in GitHub Desktop.
polynomial to string
POWERS = ['', '', '²', '³', '⁴'].freeze
def poly_to_s(coefs)
coefs.each_with_index.inject('') do |str, (coef, index)|
term = if index == 4
[coef]
else
[coef.positive? ? '+' : '-', ' ', coef.abs]
end
term << 'x' if index > 1
term << POWERS[index]
coef.zero? ? str : [term, ' ', str].join
end.strip
end
coefs = [-10.3, 24.7, 0.5086, -99.00003, -4.000002]
poly_to_s(coefs) # "-4.000002x⁴ - 99.00003x³ + 0.5086x² + 24.7 - 10.3"
def deriv_to_s(coefs)
dcoefs = coefs[1..-1].map.with_index { |c, i| c * (i+1) }
poly_to_s(dcoefs)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment