Last active
January 5, 2020 05:11
-
-
Save stephancom/f3b9a7871396cd5edf8a7f562ec324be to your computer and use it in GitHub Desktop.
polynomial to string
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
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