Chebyshev coefficients: Difference between revisions

m (→‎{{header|REXX}}: relocated a PRE ending tag.)
Line 963:
9 : -0,0000000000100189955816952521
</pre>
 
=={{header|Nim}}==
{{trans|Go}}
<lang Nim>import lenientops, math, strformat, sugar
 
type Cheb = object
c: seq[float]
min, max: float
 
 
func initCheb(min, max: float; nCoeff, nNodes: int; fn: float -> float): Cheb =
 
result = Cheb(c: newSeq[float](nCoeff), min: min, max: max)
var f, p = newSeq[float](nNodes)
let z = 0.5 * (max + min)
let r = 0.5 * (max - min)
for k in 0..<nNodes:
p[k] = PI * (k + 0.5) / nNodes
f[k] = fn(z + cos(p[k]) * r)
 
let n2 = 2 / nNodes
for j in 0..<nCoeff:
var sum = 0.0
for k in 0..<nNodes:
sum += f[k] * cos(j * p[k])
result.c[j] = sum * n2
 
 
func eval(cheb: Cheb; x: float): float =
let x1 = (2 * x - cheb.min - cheb.max) / (cheb.max - cheb.min)
let x2 = 2 * x1
var s, t: float
for j in countdown(cheb.c.high, 1):
s = x2 * t - s + cheb.c[j]
swap s, t
result = x1 * t - s + 0.5 * cheb.c[0]
 
 
when isMainModule:
let fn: float -> float = cos
let cheb = initCheb(0, 1, 10, 10, fn)
echo "Coefficients:"
for c in cheb.c:
echo &"{c: .15f}"
 
echo "\n x computed approximated computed-approx"
const N = 10
for i in 0..N:
let x = (cheb.min * (N - i) + cheb.max * i) / N
let computed = fn(x)
let approx = cheb.eval(x)
echo &"{x:.1f} {computed:12.8f} {approx:12.8f} {computed-approx: .3e}"</lang>
 
{{out}}
<pre>Coefficients:
1.647169475390314
-0.232299371615172
-0.053715114622048
0.002458235266981
0.000282119057434
-0.000007722229156
-0.000000589855645
0.000000011521427
0.000000000659630
-0.000000000010022
 
x computed approximated computed-approx
0.0 1.00000000 1.00000000 -4.685e-13
0.1 0.99500417 0.99500417 -4.620e-13
0.2 0.98006658 0.98006658 4.601e-13
0.3 0.95533649 0.95533649 -2.605e-13
0.4 0.92106099 0.92106099 -1.970e-13
0.5 0.87758256 0.87758256 4.586e-13
0.6 0.82533561 0.82533561 -1.967e-13
0.7 0.76484219 0.76484219 -2.551e-13
0.8 0.69670671 0.69670671 4.470e-13
0.9 0.62160997 0.62160997 -4.450e-13
1.0 0.54030231 0.54030231 -4.476e-13</pre>
 
=={{header|Perl}}==
Anonymous user