Home > Net >  How do I store "z" as a variable that contains more than a single value?
How do I store "z" as a variable that contains more than a single value?

Time:11-16

How do I store z as a variable with more than a single value instead of the code rewriting z after each loop?

import numpy as np

def equation1(m,k,x,deltat):

    Fpeak = 1000   9 * x**2 - 183 * x
    td = 20 - 0.12 * x**2   4.2 * x

    w = np.sqrt(k/m)
    T = 2 * np.pi / w
    time = np.arange(0,2*T,deltat)

z=[]
for t in time:
    if (t <= td):
        z = (Fpeak/k) * (1 - np.cos(w*t))   (Fpeak/k*td) * ((np.sin(w*t)/w) - t)
    else:
        z = (Fpeak/(k*w*td)) * (np.sin(w*t) - np.sin(w*(t-td))) - ((Fpeak/k) * np.cos(w*t))
    
    return(z)

print(equation1(200,1000,0,0.001))

CodePudding user response:

if you want to store multiple values in a variable use a list

z is declared as a list in your code with z = []

you can simply add to the list with the method append

z.append(value)

in your code

z=[]
for t in time:
    if (t <= td):
        z.append(((Fpeak/k) * (1 - np.cos(w*t))   (Fpeak/k*td) * ((np.sin(w*t)/w) - t)))
    else:
        z.append(((Fpeak/(k*w*td)) * (np.sin(w*t) - np.sin(w*(t-td))) - ((Fpeak/k) * np.cos(w*t)))

CodePudding user response:

It's kind of hard to understand what you are trying to do as everything is algebra, but I take it you want the end result to be a list of z values corresponding to each unit of time?

In that case replace each 'z = ...' line with 'z.append(...)' and delete the return statement.

  • Related