简体   繁体   中英

Plot sine wave (degrees)

We're supposed to plot the sine wave with the help of Matplotlib but in degrees.

First we're supposed to get every sin(x) from 0-360 degrees, every ten degrees.

I'm a beginner, would really appreciate the help.

def getsin():
    for i in range(0,361,10):
        y=math.sin(math.radians(i))
        sinvalue.append(round(y,3)
sinvalue=[]
getsin()


x=np.linspace(0,360,37)
plot.plot(x,sinvalue)
plot.xlabel("x, degrees")
plot.ylabel("sin(x)")
plot.show()

Your code is almost OK (you missed a closing parenthesis on line sinvalue.append(round(y,3) ), but it can be perfected.

Eg, it's usually considered bad practice updating a global variable (I mean sinvalue ) from inside a function... I don't say that it should never be done, I say that it should be avoided as far as possible.

A more common pattern is to have the function to return a value...

def getsin():
    sines = []
    for i in range(0,361,10):
        y=math.sin(math.radians(i))
        sines.append(round(y,3))
    return sines

Why I say this is better? Compare

sinvalue=[]
getsin()

with

sinvalue = getsin()

At least in my opinion, the second version is waaay better because it makes clear what is happening, now sinvalue is clearly the result of getting the sines...

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