Home > database >  Using a loop to calculate all possible values of a function
Using a loop to calculate all possible values of a function

Time:11-09

I want to calculate all possible values of W when it is the square root of (k / m) and k and m are a list of variables

k = arange(1, 7, 0.1)
m = arange(200, 1200, 1)

def stiff(k, m):  
    w = math.sqrt(k / m)
return w

print(stiff(k, m))

i have tried to use W = math.sqrt(k / m) but this doesn't work as the lists are of different sizes so i think i need some sort of loop or iterative method to go through this calculation for all possible values of k and m to calculate each possible value of W.

Any help would be appreciated thanks

CodePudding user response:

You can use numpy.meshgrid then create all possible combinations of two arrays then compute W like below:

import numpy as np
k = np.arange(1, 7, 0.1)
m = np.arange(200, 1200, 1)
kk , mm = np.meshgrid(k,m)
km = np.c_[kk.ravel(), mm.ravel()]
res = np.sqrt(km[:,0]/km[:,1])

Output:

>>> res
array([0.07071068, 0.07416198, 0.07745967, ..., 0.07475286, 0.07530865,
       0.07586037])

>>> len(res) , len(k), len(m)
(60000, 60, 1000)

CodePudding user response:

You can use numpy broadcasting:

import numpy as np

k = np.arange(1, 7, 0.1)
m = np.arange(200, 1200, 1)

np.sqrt(k/m[:,None])

output (2D matrix of combinations):

array([[0.07071068, 0.07416198, 0.07745967, ..., 0.18303005, 0.18439089,
        0.18574176],
       [0.07053456, 0.07397727, 0.07726674, ..., 0.18257419, 0.18393163,
        0.18527914],
       [0.07035975, 0.07379393, 0.07707525, ..., 0.18212171, 0.18347579,
        0.18481996],
       ...,
       [0.02890367, 0.03031442, 0.03166238, ..., 0.07481528, 0.07537154,
        0.07592372],
       [0.0288916 , 0.03030177, 0.03164916, ..., 0.07478405, 0.07534007,
        0.07589202],
       [0.02887955, 0.03028913, 0.03163596, ..., 0.07475286, 0.07530865,
        0.07586037]])
as 1D array:
np.sqrt(k/m[:,None]).ravel()
```
output:
```
array([0.07071068, 0.07416198, 0.07745967, ..., 0.07475286, 0.07530865,
       0.07586037])
```
  • Related