Ich habe eine glatte Funktion f (x) = sin (x/5) * exp (x/10) + 5 * exp (-x/2) Die Aufgabe ist zu erkunde eine nicht glatte Funktion h (x) = int (f (x)) im Intervall von 1 bis 30. Mit anderen Worten, jeder Wert von f (x) wird in den Typ int konvertiert, und die Funktion nimmt nur ganzzahlige Werte an. Ich versuche, h (x) mit Hilfe von Matplotlib zu bauen.TypeError beim Konvertieren eines Arrays von Floats in Ints
import math
import numpy as np
from scipy.optimize import minimize
from scipy.linalg import *
import matplotlib.pyplot as plt
def f(x):
return np.sin(x/5.0) * np.exp(x/10.0) + 5 * np.exp((-x/2.0))
def h(x):
return int(f(x))
x = np.arange(1, 30)
y = h(x)
plt.plot(x, y)
plt.show()
Der Code funktioniert nicht. Ausführen des Codes wirft
TypeError: only length-1 arrays can be converted to Python scalars
Mit VS I erhalten:
"Der Code funktioniert nicht." ist keine richtige Problembeschreibung. In diesem Fall ist es ziemlich einfach zu erraten, was der Fehler ist, aber in der Regel sind Fragen ohne korrekte Problembeschreibung off-topic. Hier ist das Problem, dass Ihre Funktion 'f' ein Array zurückgibt. Um ein numpy Array in einen Integer umzuwandeln, benötigen Sie 'array.astype (int)'. – ImportanceOfBeingErnest