2017-06-03 9 views
0

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:

enter image description here

+0

"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

Antwort

2

int eine Python-Klasse, die eine einzige int Instanz zurückgibt.

import numpy as np 
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 f(x).astype(int) 

x = np.arange(1, 30) 
y = h(x) 

plt.plot(x, y) 
plt.show() 

enter image description here

+0

Vielen Dank! – plywoods

1

Verwendung Abrunden,

def h(x): 
    return np.floor(f(x)); 

oder Rundung in Richtung Null

def h(x): 
    return np.fix(f(x)); 
: Um eine NumPy Array von Schwimmern an einer NumPy Array von ganzen Zahlen, verwenden astype(int) zu konvertieren

anstelle des implik es rundet während der Integer-Konvertierung.

+0

Vielen Dank! – plywoods

Verwandte Themen