Chebyshev coefficients: Difference between revisions
Content deleted Content added
Line 838: | Line 838: | ||
1.0 0.54030231 0.54030231 -4.477e-13 |
1.0 0.54030231 0.54030231 -4.477e-13 |
||
</pre> |
</pre> |
||
=={{header|Python}}== |
|||
{{trans|C++}} |
|||
<lang python>import math |
|||
def test_func(x): |
|||
return math.cos(x) |
|||
def mapper(x, min_x, max_x, min_to, max_to): |
|||
return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to |
|||
def cheb_coef(func, n, min, max): |
|||
coef = [0.0] * n |
|||
for i in xrange(n): |
|||
f = func(mapper(math.cos(math.pi * (i + 0.5) / n), -1, 1, min, max)) * 2 / n |
|||
for j in xrange(n): |
|||
coef[j] += f * math.cos(math.pi * j * (i + 0.5) / n) |
|||
return coef |
|||
def cheb_approx(x, n, min, max, coef): |
|||
a = 1 |
|||
b = mapper(x, min, max, -1, 1) |
|||
c = float('nan') |
|||
res = coef[0] / 2 + coef[1] * b |
|||
x = 2 * b |
|||
i = 2 |
|||
while i < n: |
|||
c = x * b - a |
|||
res = res + coef[i] * c |
|||
(a, b) = (b, c) |
|||
i += 1 |
|||
return res |
|||
def main(): |
|||
N = 10 |
|||
min = 0 |
|||
max = 1 |
|||
c = cheb_coef(test_func, N, min, max) |
|||
print "Coefficients:" |
|||
for i in xrange(N): |
|||
print " % lg" % c[i] |
|||
print "\n\nApproximation:\n x func(x) approx diff" |
|||
for i in xrange(20): |
|||
x = mapper(i, 0.0, 20.0, min, max) |
|||
f = test_func(x) |
|||
approx = cheb_approx(x, N, min, max, c) |
|||
print "%1.3f %10.10f %10.10f % 4.2e" % (x, f, approx, approx - f) |
|||
return None |
|||
main()</lang> |
|||
{{out}} |
|||
<pre>Coefficients: |
|||
1.64717 |
|||
-0.232299 |
|||
-0.0537151 |
|||
0.00245824 |
|||
0.000282119 |
|||
-7.72223e-06 |
|||
-5.89856e-07 |
|||
1.15214e-08 |
|||
6.5963e-10 |
|||
-1.00219e-11 |
|||
Approximation: |
|||
x func(x) approx diff |
|||
0.000 1.0000000000 1.0000000000 4.68e-13 |
|||
0.050 0.9987502604 0.9987502604 -9.36e-14 |
|||
0.100 0.9950041653 0.9950041653 4.62e-13 |
|||
0.150 0.9887710779 0.9887710779 -4.73e-14 |
|||
0.200 0.9800665778 0.9800665778 -4.60e-13 |
|||
0.250 0.9689124217 0.9689124217 -2.32e-13 |
|||
0.300 0.9553364891 0.9553364891 2.62e-13 |
|||
0.350 0.9393727128 0.9393727128 4.61e-13 |
|||
0.400 0.9210609940 0.9210609940 1.98e-13 |
|||
0.450 0.9004471024 0.9004471024 -2.47e-13 |
|||
0.500 0.8775825619 0.8775825619 -4.58e-13 |
|||
0.550 0.8525245221 0.8525245221 -2.46e-13 |
|||
0.600 0.8253356149 0.8253356149 1.96e-13 |
|||
0.650 0.7960837985 0.7960837985 4.53e-13 |
|||
0.700 0.7648421873 0.7648421873 2.54e-13 |
|||
0.750 0.7316888689 0.7316888689 -2.28e-13 |
|||
0.800 0.6967067093 0.6967067093 -4.47e-13 |
|||
0.850 0.6599831459 0.6599831459 -4.37e-14 |
|||
0.900 0.6216099683 0.6216099683 4.46e-13 |
|||
0.950 0.5816830895 0.5816830895 -8.99e-14</pre> |
|||
=={{header|Racket}}== |
=={{header|Racket}}== |