简体   繁体   中英

Python graphing with numpy

Okay so I'm trying to plot a function with an e to some expression but I keep getting an error at the lines that I have put (##) @ where the error message is

TypeError: unsupported operand type(s) for *: 'numpy.ufunc' and 'float'

#!C:\Users\msawe\Anaconda3 or C:\Anaconda3\python

import numpy as np
import matplotlib.pyplot as plt

plt.figure (figsize=(10,10), dpi=100)

ax = plt.subplot(111)

plt.title('Projectile Motion: Goround given by h(x) ', size=24)

ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))

def h(x):
"This function will return the y-coordinate for a given x-coordinate launch."
##return 1 - np.exp(-1* x/1000) + 0.28 *( 1 - np.exp(-0.038*x**2))*(1 - np.cos*(20*x**0.2))

X = np.linspace(0, 10, 101, endpoint=True)  

##plt.plot(X, h(X), color="black", linewidth=3, linestyle="-", label="h(x)")

plt.xlim(0,10)
plt.xticks(np.linspace(0,10,11,endpoint=True))

plt.ylim(0,20.0)
plt.yticks(np.linspace(0,20,11,endpoint=True))

plt.legend(loc='upper left', frameon=False)
plt.savefig("Ch5_P4_lowRes.png",dpi=60)
plt.savefig("Ch5_P4_hiRes.png",dpi=200)
plt.savefig("Ch5_P4_plotting.pdf",dpi=72)

plt.show()

If I could just get a general idea on how to make it work that would be great.

Assuming that I'm interpreting your equation correctly, there's a bug in your implementation of np.cos() in your definition of h(x): you wrote np.cos*(...) rather than np.cos(...) . After fixing that, the code is able to plot- hopefully it's giving the right result!

This would turn your definition of h(x) from:

def h(x):
    return 1 - np.exp(-1* x/1000) + 0.28 *( 1 - np.exp(-0.038*x**2))*(1 - np.cos*(20*x**0.2))

Into:

def h(x):
    return 1 - np.exp(-1* x/1000) + 0.28 *( 1 - np.exp(-0.038*x**2))*(1 - np.cos(20*x**0.2))

The difference is subtle but important! You can easily check for bugs like this by running successively smaller segments of your code to see which operation is throwing the error- this let me quickly hone in on the np.cos*(...) typo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM