如何用python求差商?
問(wèn)題描述
假設(shè)有一個(gè)點(diǎn)集[x0, x1, x2, ..., xn],對(duì)應(yīng)的函數(shù)值為[y0, y1, y2, ..., yn],怎樣求差商(1至n階)。
k階差商計(jì)算公式 f(x0, x1, ..., xk) = (f(x1, x2, ..., xk) - f(x0, x1, ... x(k-1))) / (xk - x0)舉個(gè)例子,一階差商: 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)
問(wèn)題解答
回答1:大概是這樣:
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)
結(jié)果:
f(3)=3f(2)=2f(2, 3)=(f(3)-f(2))/(3-2)=1.0f(2)=2f(1)=1f(1, 2)=(f(2)-f(1))/(2-1)=1.0f(1, 2, 3)=(f(2, 3)-f(1, 2))/(3-1)=0.0
我回答過(guò)的問(wèn)題: Python-QA
相關(guān)文章:
1. docker不顯示端口映射呢?2. angular.js - 關(guān)于$apply()3. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””4. macos - mac下docker如何設(shè)置代理5. MySQL數(shù)據(jù)庫(kù)中文亂碼的原因6. docker - 各位電腦上有多少個(gè)容器啊?容器一多,自己都搞混了,咋辦呢?7. docker gitlab 如何git clone?8. mysql - 新浪微博中的關(guān)注功能是如何設(shè)計(jì)表結(jié)構(gòu)的?9. css - C#與java開(kāi)發(fā)Windows程序哪個(gè)好?10. docker-compose 為何找不到配置文件?
