我根據給定的簡單正弦函式構造了一個牛頓多項式。實施了中間計算,但在最后階段停止 - 獲得多項式的公式。遞回在這里可能會有所幫助,但它是不準確的。這是多項式的公式
該公式迭代下表中的值:我們遍歷 x 的列和計算出的增量的第一行(我們上到增量,我們得到多項式的次數)。例如,如果度數為 2,那么我們將在第一行取 2 個增量,在 x 列中取 2.512 的值(9 個帶有 x 差異的括號將在多項式的最后一個塊中)
在公式中,有一組常量塊在其中迭代值,但我在元素 (x —x_0)**[n] 中有一個障礙。這是用戶設定的多項式 n 的次數。這里[n]表示括號中的運算式被展開:
我使用sympy庫進行符號計算:未來多項式的公式中的x應該保持x(作為一個符號,而不是它的值)。如何實作在多項式中重復的塊的一部分,該多項式隨著多項式次數的新括號而增長?
代碼:
import numpy as np
from sympy import *
import pandas as pd
from scipy.special import factorial
def func(x):
return np.sin(x)
def poly(order):
# building columns X and Y:
x_i_list = [round( (0.1*np.pi*i), 4 ) for i in range(0, 11)]
y_i_list = []
for x in x_i_list:
y_i = round( (func(x)), 4 )
y_i_list.append(y_i)
# we get deltas:
n=order
if n < len(y_i_list):
result = [ np.diff(y_i_list, n=d) for d in np.arange(1, len(y_i_list)) ]
print(result)
else:
print(f'Determine the order of the polynomial less than {len(y_i_list)}')
# We determine the index in the x column based on the degree of the polynomial:
delta_index=len(result[order-1])-1
x_index = delta_index
h = (x_i_list[x_index] - x_i_list[0]) / n # calculate h
b=x_i_list[x_index]
a=x_i_list[0]
y_0=x_i_list[0]
string_one = [] # list with deltas of the first row (including the degree column of the polynomial)
for elen in result:
string_one.append(round(elen[0], 4))
# creating a list for the subsequent passage through the x's
x_col_list = []
for col in x_i_list:
if col <= x_i_list[x_index]:
x_col_list.append(col)
x = Symbol('x') # for symbolic representation of x's
# we go along the deltas of the first line:
for delta in string_one:
# we go along the column of x's
for arg in x_col_list:
for n in range(1, order 1):
polynom = ( delta/(factorial(n)*h**n) )*(x - arg) # Here I stopped
uj5u.com熱心網友回復:
我猜你正在尋找這樣的東西:
In [52]: from sympy import symbols, prod
In [53]: x = symbols('x')
In [54]: nums = [1, 2, 3, 4]
In [55]: prod((x-n) for n in nums)
Out[55]: (x - 4)?(x - 3)?(x - 2)?(x - 1)
編輯:實際上這樣做更有效,Mul
而不是prod
:
In [134]: Mul(*((x-n) for n in nums))
Out[134]: (x - 4)?(x - 3)?(x - 2)?(x - 1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/487135.html