我如何使用python用方程中的浮点替换变量

2024-04-25 21:59:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个代码来计算仪器课程的错误传播。代码要求您输入方程式、包含错误的变量、它们的值和不确定性。然后根据输入的变量导出方程,并将其存储在列表中。我试图用它们的值替换导出方程的变量,用不确定性乘以整个运算,然后对列表中的每个索引重复这个过程。然后我想求这个列表中所有索引的平方根之和,得到误差传播的值。 我被困在替换导出方程中变量的值上,需要帮助。我尝试了re.sub()和.replace(),但是它们不起作用,因为我试图用一个浮点替换它们。我将发布代码和输出。谢谢你的帮助

代码:

from sympy import diff, Symbol
from sympy.parsing.sympy_parser import parse_expr
print('Propagation of error: ')
exp=str(input('Enter the expression to find the propagation of error: '))
var=list(map(str,input('Enter the variables containing uncertainty seperated by spaces: ').split())) 
val=list(map(float,input('Enter the values of the variables in the same order seperated by spaces: ').split()))
x=list(map(float,input('Enter the values of the uncertainty of each variable in the same order seperated by spaces: ').split())) 
L=[]
for i in range(len(var)):  
    symb={var[i]:Symbol(var[i],real=True)}
    func=parse_expr(exp,symb)
    L.append(diff(func,symb[var[i]]))
print(L)

输出

enter image description here


1条回答
网友
1楼 · 发布于 2024-04-25 21:59:37

操作代码问题

带字符串的表达式是:3*E**2+5*K*E**3

  • 您一次只能使用一个符号来解析字符串表达式,即K,e
  • 第一个循环使用符号K,而不是E。因此E被解释为exp()
  • 然后,关于K的部分变为5*exp(3)

传播误差的计算

Source

对于a、b、c中三个变量的函数,即:

enter image description here

传播误差的平方为:

enter image description here

这里,我们想把它应用到两个变量的函数:K,E

代码

from sympy import diff, Symbol
from sympy.parsing.sympy_parser import parse_expr

# Setup
print('Propagation of error: ')
exp = input('Enter the expression to find the propagation of error: ')
var = input('Enter the variables containing uncertainty seperated by spaces: ').split()
values = [float(v) for v in input('Enter the values of the variables in the same order seperated by spaces: ').split()]
undertainties = [float(v) for v in input('Enter the values of the uncertainty of each variable in the same order seperated by spaces: ').split()]

# Create Symbol Table for variables 
#   (i.e. dictionary of variable names mapped to sympy symbols)
symb = {x:Symbol(x, real = True) for x in var}  

# Table for values of symbols (i.e. dictionary of symbols mapped to values)
val_table = {symb[x]:v for x, v in zip(var, values)}

# Symbolic expression using symbol table
func = parse_expr(exp, symb)  

# List of partial derivatives
derivatives = [diff(func, symb[x]) for x in var]

# Error is sum of partials squared times undertainty squared
# Use val_table for local values for symbols
error = sum((u**2)*d.evalf(subs=val_table)**2 for u, d in zip(undertainties, derivatives))
print(f'Propgation error is: {error**0.5}')  # Square root of sum of squares

输出

Propagation of error: 
Enter the expression to find the propagation of error: 3*E**2+5*K*E**3
Enter the variables containing uncertainty separated by spaces: K E
Enter the values of the variables in the same order separated by spaces: 10 15
Enter the values of the uncertainty of each variable in the same order separated by spaces: 0.1 0.15
Propagation error is: 5349.15247959899

相关问题 更多 >