Thread: 1D Linear Convection Python View Single Post
Mentor
P: 21,280
1D Linear Convection Python

 Quote by Jonny6001 Formatted your code using [ code] [ /code] block (without the leading space). [code] nx=20, nt=50 dt=0.01, c=1 dx=2/(nx-1) for i in (1,nx): if 0.5<=x(i)<=1: // see comment 1 below u(i)=2 else: u(i)=1 end end for it in (1,nt): un=u // see comment 2 below for i in (2,nx-1): u(i)=un(i)-c*dt/dx(un(i)-un(i-1)) // see comment 3 end end [\code] Sorry about that, it didn't cross my mind. Thank you
Caveat: I don't know python, but I'm very familiar with C, C++, C#, and a slew of other programming languages.

1. I'm 99% sure you can't do this. 0.5<=x(i)<=1 is strictly mathematics notation shorthand. Your intent is clear, but you can't do it this way. To check that x(i) is between 0.5 and 1.0, do this:
if ( x(i) >= 0.5 && x(i) <= 1.0)
{
...
}
else
{
...
}
What I've written is C/C++ syntax, so you'll need to modify it a bit for Python. The else clause is executed when the expression in the if clause is false; i.e., when x(i) < 0.5 OR when x(i) > 1.0. If you need to take different actions for these then you need an elseif (or maybe it's elif in python - don't know) and an else clause.

2. What is un = u doing? Both of these appear to be arrays. If arrays in python work anything like they do in C, what this is doing is to put the address of the u array into un.

3. In this line, u(i)=un(i)-c*dt/dx(un(i)-un(i-1)), you're missing a multiplication operator - *. It should be u(i)=un(i)-c*dt/dx * (un(i)-un(i-1))

 Quote by Jonny6001 I can more or less input this in a form that Python understands but I'm not quite sure how to start off the loops with a value of 'i' and maybe I need to add and increment to 'i' once it has done the loop once? I mean for a start, I should be able to run the first for loop which says for values of i between 0.5 and 1, the value of 'ui' will be 2, everywhere else ui=1.
I don't understand what you're asking about the loop variables. In your first loop i takes on values of 1, 2, 3, ..., 19, 20. In the second loop in takes on values of 1, 2, 3, ..., 50.

Also, in your first loop, if x(i) (not i) is between .5 and 1, u(i) (not ui) gets set to 2; otherwise u(i) gets set to 1. Try to be more precise in what you say.

Finally, in your nested loop, what are you trying to do? The outer loop runs 50 times, and each iteration of the outer loop causes the inner loop to run 18 times. This means that each statement in the inner loop runs 50 * 18 = 900 times.