Home > OS >  How to create this function with a for loop?
How to create this function with a for loop?

Time:12-15

For some reason I cannot get my head around how to create the below function in a more concise way, I'm thinking I need to use a for loop but I'm really struggling to implement this. Any help at all would be appreciated, I'm very much a beginner with python!

x = np.linspace(0, 20, 100)
f1 = (((-1)**((1 - 1)/2)) / (1**2)) * np.sin((1 * np.pi * x) / 10)
f3 = (((-1)**((3 - 1)/2)) / (3**2)) * np.sin((3 * np.pi * x) / 10)
f5 = (((-1)**((5 - 1)/2)) / (5**2)) * np.sin((5 * np.pi * x) / 10)
f7 = (((-1)**((7 - 1)/2)) / (7**2)) * np.sin((7 * np.pi * x) / 10)
f9 = (((-1)**((9 - 1)/2)) / (9**2)) * np.sin((9 * np.pi * x) / 10)
f11 = (((-1)**((11 - 1)/2)) / (11**2)) * np.sin((11 * np.pi * x) / 10)
f13 = (((-1)**((13 - 1)/2)) / (13**2)) * np.sin((13 * np.pi * x) / 10)
f15 = (((-1)**((15 - 1)/2)) / (15**2)) * np.sin((15 * np.pi * x) / 10)

CodePudding user response:

x = np.linspace(0,20,100)
f = []
for i in range(1, 16, 2):
    f.append((((-1)**((i-1)/2))/(i**2))*np.sin((i*np.pi*x)/10))

would that work?

CodePudding user response:

You would have to do something like this:

l = []
x = np.linspace(0,20,100)
for i in range(1, 16, 2):
    l.append((((-1)**((i-1)/2))/(i**2))*np.sin((i*np.pi*x)/10))

CodePudding user response:

If you're looking for a vectorized function that can take one or more arguments (call it a), and an optional replacement for x, you can do:

def f(a, x=None):
    if x is None:
        x = np.linspace(0, 20, 100)
    a = np.array(a, copy=False, ndmin=1)[..., None]
    return (((-1)**((a - 1) / 2)) / (a**2)) * np.sin((a * np.pi * x) / 10)

Broadcasting the arrays together makes it so you don't need to run an explicit loop. You could call f as

f(np.arange(1, 16, 2))

or

f(1)
f(3)
f(5)
...

In fact, you can check that

 np.array_equal(f(np.arange(1, 16, 2)), [f1, f3, f5, f7, f9, f11, f13, f15])

CodePudding user response:

x = np.linspace(0,20,100)
i = 1
dictAnswer={}
while i < 50:
    answer = (((-1)**((i-1)/2))/(i**2))*np.sin((i*np.pi*x)/10) 
    dictAnswer[f'f{i}'] = answer
    i =2

This loop will run until f49. You can change the while i < 50 as per your need. Now this will save all the answers in a dictionary. You can see the answers as: print(dictAnswer[f1]).

Mind be that this will not print out the entire string but rather just the exact required answer of the formula

  • Related