search

Home  >  Q&A  >  body text

如何用python求差商?

假设有一个点集[x0, x1, x2, ..., xn],对应的函数值为[y0, y1, y2, ..., yn],怎样求差商(1至n阶)。

k阶差商计算公式
f(x0, x1, ..., xk) = (f(x1, x2, ..., xk) - f(x0, x1, ... x(k-1))) / (xk - x0)
举个例子,一阶差商:
f(x0, x1) = (f(x1) - f(x0)) / (x1 - x0)
f(x1, x2) = (f(x2) - f(x1)) / (x2 - x1)
二阶差商:
f(x0, x1, x2) = (f(x1, x2) - f(x0, x1)) / (x2 - x1)

迷茫迷茫2785 days ago960

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 10:29:15

    Probably like this:

    fmap = {1:1, 2:2, 3:3}
    
    def f(*x):
        if len(x)==1:
            rc = fmap[x[0]]
            print('f({})={}'.format(x[0], rc))
            return rc
        rc = (f(*x[1:])-f(*x[:-1]))/(x[-1]-x[0])
        template = 'f({})=(f({})-f({}))/({}-{})={}'
        print(template.format(', '.join([str(i) for i in x]),
                              ', '.join([str(i) for i in x[1:]]),
                              ', '.join([str(i) for i in x[:-1]]),
                              x[-1], x[0],
                              rc))
        return rc
        
    f(1, 2, 3)

    Result:

    f(3)=3
    f(2)=2
    f(2, 3)=(f(3)-f(2))/(3-2)=1.0
    f(2)=2
    f(1)=1
    f(1, 2)=(f(2)-f(1))/(2-1)=1.0
    f(1, 2, 3)=(f(2, 3)-f(1, 2))/(3-1)=0.0

    Questions I answered: Python-QA

    reply
    0
  • Cancelreply