如何使用這個方程:
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)
uj5u.com熱心網友回復:
當您將 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.
uj5u.com熱心網友回復:
您傳遞給函式的 x 和 y 可能不是整數/浮點數,這取決于您在函式中使用 cos 的方式,它們應該是整數/浮點數。只需通過列印它們來檢查您的 x 和 y 是否真的是您所期望的。如果它們最終成為串列,只需遍歷串列并為每對 x 和 y 呼叫您的函式,或者如果您期望 x 和 y 有一個奇異值,那么您需要重新考慮在 f 之前您在做什么(x, y) 呼叫。似乎對您在自定義函式呼叫之前使用的其中一個函式實際上在做什么存在誤解。
uj5u.com熱心網友回復:
from math import cos
def f(x,y):
return ( (7/10)*x**4 - 8*y**2 6*y**2 cos(x*y) - 8*x)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/477172.html
