import numpy as np
Write code to print the numbers 0 to 4 on each line below.
print(0)
print(1)
print(2)
print(3)
print(4)
0 1 2 3 4
for i in range(10):
print(i)
0 1 2 3 4 5 6 7 8 9
i
can be any variable, not just "i"For the ideal gas law, pressure is given by $$P = nRT/V$$
For V = 2, 3, 4, 5, ... 20, use a loop to find and print the values of P for each V.
n = 1
R = 8314
T = 300
for V in range(2,21):
P = n*R*T/V
print(P)
1247100.0 831400.0 623550.0 498840.0 415700.0 356314.28571428574 311775.0 277133.3333333333 249420.0 226745.45454545456 207850.0 191861.53846153847 178157.14285714287 166280.0 155887.5 146717.64705882352 138566.66666666666 131273.68421052632 124710.0
Add all the numbers from 0 to 100
s = 0
for i in range(101):
s = s + i
print(s)
5050
for
loop. Even another loop.for i in range(3):
print(f"i={i}")
for j in range(4):
print(f" j={j}")
for i in range(3):
print(f"i={i}")
for j in range(4):
print(f" j={j}")
i=0 j=0 j=1 j=2 j=3 i=1 j=0 j=1 j=2 j=3 i=2 j=0 j=1 j=2 j=3
we can use Newton's method to find $x$ for $f(x)=0$.
Excel | Python |
---|---|
cell for guess | ?? |
Newton equation in terms of x cell A2 - (A2^2-3)/(2*A2) |
?? |
repeat: fill down | ?? |
x = 1
for i in range(6):
x = x - (x**2 - 3)/(2*x)
print(x)
2.0 1.75 1.7321428571428572 1.7320508100147276 1.7320508075688772 1.7320508075688774
i
is not being used, it is just for convenience in creating the loop.x
is used on both sides of the equation. It is reused.Excel | Python |
---|---|
cell for guess | variable for x |
Newton equation in terms of x cell A2 - (A2^2-3)/(2*A2) |
Newton equation in terms of x x = x - (x**2-3)/(2*x) |
repeat: fill down | repeat: wrap in loop |
# step 1: initial guess
x = 1
# step 2: add Newton equation
x=1
x = x - (x**2 - 3)/(2*x)
# step 3: wrap in loop
x=1
for i in range(6):
x = x - (x**2 - 3)/(2*x)
# step 4: add a print
x=1
for i in range(6):
x = x - (x**2 - 3)/(2*x)
print(x)
2.0 1.75 1.7321428571428572 1.7320508100147276 1.7320508075688772 1.7320508075688774
Redo Solution 1 using functions for $f(x)$ and $f^\prime(x)$.
def f(x):
return x**2 - 3
def fprime(x):
return 2*x
x = 1
for i in range(6):
x = x - f(x)/fprime(x)
print(f"after iteration {i+1}, x={x:.4f}")
after iteration 1, x=2.0000 after iteration 2, x=1.7500 after iteration 3, x=1.7321 after iteration 4, x=1.7321 after iteration 5, x=1.7321 after iteration 6, x=1.7321
Modify the code above to do just the right number of iterations.
def f(x):
return x**2 - 3
def fprime(x):
return 2*x
xold = 1
for i in range(6):
xnew = xold - f(xold)/fprime(xold)
err = np.abs( (xnew-xold) / xnew )
if np.abs(err < 1E-3):
break
print(f"after iteration {i+1}, x={xnew:.4f}")
xold = xnew
after iteration 1, x=2.0000 after iteration 2, x=1.7500 after iteration 3, x=1.7321
xold
and xnew
.xold=xnew
at the end to get set for next interation.break
np.abs()