2025年3月8日 星期六

用泰勒展開式逼近一個 cos 函數

import autograd as auto_grad
import autograd.numpy as audo_np
import matplotlib.pyplot as plt

def taylor_bind(f, nth = 15, a = 0.0):
    def g(x) : # order-n taylor series, f(x) = Σₙ[fⁿ(0) * xⁿ / n!]
        if nth < 0:# todo
            return 0
        elif nth == 0:# todo
            return 1
        elif nth == 1:
            return f(a)
        taylor_sum = f(a) # initial value when order-n > 1
        d_f = auto_grad.elementwise_grad(f) # inital derivative term
        xpow = x - a # inital power term
        n_ = 1 # inital factorial term
        k = 1 # iteration from 1, upto n
        while True : # iteration begin, 開始疊代
            taylor_sum += d_f(a) * xpow / n_
            k += 1 # pipe next
            if k == nth: # no need to run while upto nth
                break
            d_f = auto_grad.elementwise_grad(d_f) # next derivative of f
            xpow *= (x - a) # next power of (x - a)
            n_ *= k # next factorial
        return taylor_sum
    return g # function can be run in the future

x0 = audo_np.linspace(-7, 7, 500)
y1 = audo_np.cos
y2 = taylor_bind(y1)
plt.plot(x0, y2(x0), color="g", label="taylor_bind")
plt.plot(x0, y1(x0), color="r", label="cos")
plt.xlabel("x")
plt.title("Taylor series fit")
plt.legend() # to show the multi label
plt.show()

沒有留言:

張貼留言

使用 python 簡單實現多 cpu 平行處理

 import multiprocessing as mp import time def iso_task(k):     print(f"task {k} @{time.time()} sec: sleep for 1 second")     time....