Polynomial derivative: Difference between revisions

→‎{{header|Wren}}: Now prints polynomials in 'normal' notation too.
m (→‎{{header|Raku}}: trap an edge condition for exponents > 9 (doesn't matter here))
(→‎{{header|Wren}}: Now prints polynomials in 'normal' notation too.)
Line 172:
}
 
var ss = ["", "", "\u00b2", "\u00b3", "\u2074", "\u2075", "\u2076", "\u2077", "\u2078", "\u2079"]
System.print("The derivatives of the following polynomials are:")
 
// for n <= 20
var superscript = Fn.new { |n| (n < 10) ? ss[n] : (n < 20) ? ss[1] + ss[n - 10] : ss[2] + ss[0] }
 
var polyPrint = Fn.new { |p|
if (p.count == 1) return p[0].toString
var terms = []
for (i in 0...p.count) {
if (p[i] == 0) continue
var x = (i > 0) ? "x" : ""
terms.add("%(p[i])%(x)%(superscript.call(i))")
}
return terms[-1..0].join("+").replace("1x", "x").replace("+-", "-")
}
 
System.print("The derivatives of the following polynomials are:\n")
var polys = [ [5], [4, -3], [-1, 6, 5], [-4, 3, -2, 1], [1, 1, 0, -1, -1] ]
for (poly in polys) {
var deriv = derivative.call(poly)
System.print("%(poly) -> %(deriv)")
}
System.print("\nOr in normal mathematical notation:\n")
for (poly in polys) {
var deriv = derivative.call(poly)
System.print("Polynomial : %(polyPrint.call(poly))")
System.print("Derivative : %(polyPrint.call(deriv))\n")
}</lang>
 
Line 182 ⟶ 204:
<pre>
The derivatives of the following polynomials are:
 
[5] -> [0]
[4, -3] -> [-3]
Line 187 ⟶ 210:
[-4, 3, -2, 1] -> [3, -4, 3]
[1, 1, 0, -1, -1] -> [1, 0, -3, -4]
 
Or in normal mathematical notation:
 
Polynomial : 5
Derivative : 0
 
Polynomial : -3x+4
Derivative : -3
 
Polynomial : 5x²+6x-1
Derivative : 10x+6
 
Polynomial : x³-2x²+3x-4
Derivative : 3x²-4x+3
 
Polynomial : -x⁴-x³+x+1
Derivative : -4x³-3x²+1
</pre>
9,486

edits