如何在函数内使用全局变量(导数表达式)

How to use a global variable (derivative expression) inside a function

这个脚本非常适合我想要的。这是我想要最小化的权重函数。我在函数内部和全局范围内编写,我注意到全局 print(W) 是我的表达式,函数内部的 print(W) 是要绘制的值数组:

import numpy as np
from sympy import *
import matplotlib.pyplot as plt

#Weight function

tf = Symbol('tf')
l = 50/(0.54*tf) - tf
d = (tf*(2*l+2*(l-tf)/2))/(2*l*(l+tf)/2)
W = 15.7*tf-7.85*tf*d+7.85*d*50/(0.54*tf)
print(W)

def func(tf):
    l = 50/(0.54*tf) - tf
    d = (tf*(2*l+2*(l-tf)/2))/(2*l*(l+tf)/2)
    W = 15.7*tf-7.85*tf*d+7.85*d*50/(0.54*tf)
    print(W)
    return W

b = np.linspace(1, 10, 201)
plt.plot(b, func(b))
plt.xlabel("tf", fontsize=18)
plt.ylabel("Weight", fontsize=18)
plt.grid()
plt.show()

我的问题现在发生了。我也想绘制权重函数导数。但是我不能在函数内部执行它,因为它识别为数字(数组的第一个元素)。第一个打印给了我想要绘制的表达式,但我无法在函数内部发送该表达式。如何调用函数内部使用的全局变量(导数表达式)?

dW_dtf = W.diff(tf)
print(dW_dtf)

def funcd(tf):
    l = M/(a*tf) - tf
    tw = tf
    d = (tw*(2*l+2*(l-tw)/2))/(2*l*(l+tw)/2)
    W = 15.7*tf-7.85*tf*d+7.85*d*M/(a*tf)
    dW_dtf = W.diff(tf)
    return dW_dtf

A​​ttributeError: 'numpy.ndarray' 对象没有属性 'diff'

我愿意接受其他选择来做我想做的事。我将阅读更多有关使用 python 的优化算法的信息,因为我将不得不解决更困难的问题,但我想在不使用迭代方法的情况下解决此类基本问题。谢谢你。路易斯

在您的代码中,您实质上是在覆盖您的全局定义。现在,当您调用 func 时,您使用提交为 tf 的任何值重新定义了 W。在你的例子中,一个数组。这样一来,W 就不再是一个符号表达式,而是一个数组。你想要的是这样的东西而不是 func:

def func(x):
    w_evaluator=lambdify(tf,W)
    return w_evaluator(x)

类似地:

def funcd(x):
     dwdt_evaluator=lambdify(tf,W.diff(tf))
     return dwdt_evaluator(x)