【发布时间】:2023-02-10 18:27:46
【问题描述】:
我的问题和我之前question的回答有关。
以前的解决方案中的代码和这个问题的当前代码之间的区别如下:在我的代码中,我必须设置函数“myfunc”返回两个不同的结果,
if t==0: return(10) else: return np.sqrt(r**2 - t**2) 而不是只有一个回报: return np.sqrt(r**2 - t**2) 。
知道如果你运行文件它会引发 ValueError,
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
有人可以向我解释如何解决这个问题,而不更改函数以返回一个结果,因为我需要让它返回两个结果,这只是我遇到的问题的一个例子,我正在编写的程序与这个有很大不同.
太感谢了
from matplotlib import pyplot as plt
import numpy as np
# create the function (which you may not have access to)
def myfunc(t, r=1.0):
if t==0:
return (10)
else:
return np.sqrt(r**2 - t**2)
# generate some points at which the function has been evaluate
t = np.linspace(0, 1, 100) # 100 points linearly spaced between 0 and 1
y = myfunc(t) # the function evaluated at the points t
# assuming we just have t and y (and not myfunc), interpolate the value of
# the function at some point t1
t1 = 0.68354844
y1 = np.interp(t1, t, y)
# use piecewise to get a function which is constant below t1 and follows the
# original function above t1 (potentially evaluated at different points in t)
tnew = np.linspace(0, 1, 150) # new (more highly sampled) points at which to evaluate the function
condlist = [tnew <= t1, tnew > t1] # list of piecewise conditions
funclist = [y1, np.interp] # use constant y1 for first condition and interp for second condition
# evaluate the piecewise function at tnew
yvals = np.piecewise(tnew, condlist, funclist, t, y)
# plot the original function and the new version with the constant section
fig, ax = plt.subplots()
ax.plot(t, y, label="Original function")
ax.plot(tnew, yvals, ls="--", label="Piecewise function")
ax.legend()
fig.show()
我仍然是一般编程的初学者,所以请,如果你能写一个我容易理解的答案,那将非常有帮助,我真的很感激。
【问题讨论】:
-
t将是一个值数组。如果t包含 0,您是否希望myfunc仅返回单个值10?或者您是否仍希望myfunc返回一个值数组,只是索引等同于t为零且包含值 10 的位置?
标签: python numpy matplotlib valueerror