如何使用包含此产品的功能?
How to work with the function that contains this product?
如何使用这个等式:
def f(x,y):
return ( (7/10)*x**4 - 8*y**2 + 6*y**2 + cos(x*y) - 8*x)
x = np.linspace(-3.1416,3.1416,100)
y = np.linspace(-3.1416,3.1416,100)
x,y = np.meshgrid(x,y)
z = f(x,y)
TypeError: only size-1 arrays can be converted to Python scalars
问题出在 cos(x*y)
您传递给函数的 x 和 y 可能不是 ints/floats,这取决于您在函数中使用 cos 的方式,它们应该是 ints/floats。只需通过打印出来检查您的 x 和 y 是否确实符合您的预期。如果它们最终成为列表,只需遍历列表并为每对 x 和 y 调用您的函数,或者如果您期望 x 和 y 的奇异值,那么您需要重新考虑您在 f 之前所做的事情(x, y) 呼叫。似乎对您在自定义函数调用之前使用的某个函数的实际作用存在误解。
将 numpy 数组传递给 math.cos
时出现该错误。
>> import math
>> import numpy as np
>> x = np.random.random((3,3))
>> math.cos(x)
TypeError: only size-1 arrays can be converted to Python scalars
但是如果你使用np.cos
,你会得到x
的每个元素的余弦值。
>> np.cos(x)
array([[0.77929073, 0.98196607, 0.99423945],
[0.99542772, 0.93156929, 0.8161034 ],
[0.62669568, 0.92407875, 0.76850767]])
所以不要将您的 numpy 数组传递给 math.cos
。传递给 numpy.cos
.
如何使用这个等式:
def f(x,y):
return ( (7/10)*x**4 - 8*y**2 + 6*y**2 + cos(x*y) - 8*x)
x = np.linspace(-3.1416,3.1416,100)
y = np.linspace(-3.1416,3.1416,100)
x,y = np.meshgrid(x,y)
z = f(x,y)
TypeError: only size-1 arrays can be converted to Python scalars
问题出在 cos(x*y)
您传递给函数的 x 和 y 可能不是 ints/floats,这取决于您在函数中使用 cos 的方式,它们应该是 ints/floats。只需通过打印出来检查您的 x 和 y 是否确实符合您的预期。如果它们最终成为列表,只需遍历列表并为每对 x 和 y 调用您的函数,或者如果您期望 x 和 y 的奇异值,那么您需要重新考虑您在 f 之前所做的事情(x, y) 呼叫。似乎对您在自定义函数调用之前使用的某个函数的实际作用存在误解。
将 numpy 数组传递给 math.cos
时出现该错误。
>> import math
>> import numpy as np
>> x = np.random.random((3,3))
>> math.cos(x)
TypeError: only size-1 arrays can be converted to Python scalars
但是如果你使用np.cos
,你会得到x
的每个元素的余弦值。
>> np.cos(x)
array([[0.77929073, 0.98196607, 0.99423945],
[0.99542772, 0.93156929, 0.8161034 ],
[0.62669568, 0.92407875, 0.76850767]])
所以不要将您的 numpy 数组传递给 math.cos
。传递给 numpy.cos
.