简体   繁体   中英

Using numpy to simplify functions

I am quite new to numpy. I was wondering if there is a easier way to run this code without using loops by using numpy.

def summer(n):
    list1 = []
    mysum = 0

    for i in range(1,n+1):#making a random number up to n in a list
        list1.append(random())
    for j in range(0,len(list1),2):
        mysum = mysum + (math.sin(list1[j]) * math.cos(list1[j+1]))
    return mysum
print(summer(100))

currently I have only found a good way to create the random list of numbers using:

rand = np.random.random(n)

Yes, that's pretty straightforward in numpy, and certainly faster:

def summer(n):
    return (np.sin(np.random.rand(int(n/2))) * np.sin(np.random.rand(int(n/2)))).sum()

Note that I split list1 in 2 lists, as indices of list1 were only used once and list1 was an internal variable, it does not change the result.

Edit: If the question is about getting elements of an array with only odd or even indices, they can be obtained with my_array[::2] and my_array[1::2] .

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