简体   繁体   中英

Passing parameters to a function in Python

I started programming two weeks ago, so I realize this might be a stupid question. I want to find the y values for the t values in the interval [0,25], without using a for loop. I want a list of y values, but instead I get <function y at 0x01D4D5D0> :

from math import cos, e, sqrt
import numpy as np
m = 9          
A = 0.3         
k = 4          
gamma = 0.15

t_array = np.linspace(0,25)
y_array = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
def y(t_array):
    y = []
    y.append(A*(e**(-gamma)**(t_array))*cos((sqrt(k/m))*(t_array)))
print(y)

Your original problem arises due to the fact that you don't call the function you define. You cannot expect a function to know what arguments it must work with. Python is procedural; you must pass those arguments yourself.

Alternatively (and I recommend this), you could just use numpy 's ufuncs and vectorise everything:

y_array = A * (np.exp(-gamma) ** (t_array)) * np.cos((np.sqrt(k / m)) * (t_array))

print(y_array)
array([ 0.3       ,  0.26197643,  0.20012117,  0.12471753,  0.04610095,
       -0.02650152, -0.08584334, -0.12718585, -0.14847109, -0.1501709 ,
       -0.13487525, -0.10670268, -0.07062388, -0.03178614,  0.00508595,
        0.03615761,  0.05878548,  0.07164338,  0.07468336,  0.06895966,
        0.05635461,  0.03925115,  0.0201959 ,  0.00159182, -0.01454951,
       -0.02677677, -0.03428127, -0.03689604, -0.0350233 , -0.02950888,
       -0.02148485, -0.01220259, -0.00287629,  0.0054473 ,  0.01198185,
        0.0162522 ,  0.01810327,  0.0176719 ,  0.01533013,  0.01161037,
        0.00712318,  0.00247811, -0.00178419, -0.00524252, -0.00762514,
       -0.00881889, -0.00885931, -0.00790559, -0.00620522, -0.00405386]

Disclaimer : I cannot verify this answer because you have not explained what you are trying to do. This should hopefully get you started in the right direction working with vectorisation.

i think the problem is that you have a function called 'y' and printing y prints the function location. Also the function y is not ran only defined and it does not return anything as well. So to print the newly created y list inside the y function you can do:

def y(t_array):
    y_values = []
    y_values.append(A*(e**(-gamma)**(t_array))*cos((sqrt(k/m))*(t_array)))
    return y_values
print(y(t_array))

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