1

I was just solving a problem using python, and my codes are:

from math import sin,pi
import numpy
import numpy as np
import pylab
N=20
x = np.linspace(0,1, N)
def v(x):
    return 100*sin(pi*x)

#set up initial condition
u0 = [0.0]              # Boundary conditions at t= 0
for i in range(1,N):
    u0[i] = v(x[i])

And I would want to plot the results by updating v(x) in range(0, N) after. it looks simple but perhaps you guys could help since it gives me an error, like

Traceback (most recent call last):
  File "/home/universe/Desktop/Python/sample.py", line 13, in <module>
    u0[i] = v(x[i])
IndexError: list assignment index out of range

3 Answers 3

1

You could change u0[i] = v(x[i]) to u0.append(v(x[i])). But you should write more elegantly as

u0 = [v(xi) for xi in x]

Indices i are bug magnets.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very big guys as all the codes here are all working
1

Since you are using numpy, I'd suggest using np.vectorize. That way you can pass the array x directly to the function and the function will return an array of the same size with the function applied on each element of the input array.

from math import sin,pi
import numpy
import numpy as np
import pylab
N=20
x = np.linspace(0,1, N)
def v(x):
    return 100*sin(pi*x)

vectorized_v = np.vectorize(v) #so that the function takes an array of x's and returns an array again
u0 = vectorized_v(x) 

Out:

array([  0.00000000e+00,   1.64594590e+01,   3.24699469e+01,
         4.75947393e+01,   6.14212713e+01,   7.35723911e+01,
         8.37166478e+01,   9.15773327e+01,   9.69400266e+01,
         9.96584493e+01,   9.96584493e+01,   9.69400266e+01,
         9.15773327e+01,   8.37166478e+01,   7.35723911e+01,
         6.14212713e+01,   4.75947393e+01,   3.24699469e+01,
         1.64594590e+01,   1.22464680e-14])

Comments

0

u is a list with one element, so you can't assign values to indices that don't exist. Instead make u a dictionary

u = {}
u[0] = 0.0
for i in range(1,N):
    u[i] = v(x[i])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.