G
G
Gleb2020-09-29 21:02:36
Python
Gleb, 2020-09-29 21:02:36

1) Why are the graphs different? 2) Is there a function to write an element to an array in a loop?

Part 1 of the question, I solved the equation with an exact and numerical method, checked it on Wolfram, then compiled and expressed the recursive equation (replacement: y'' with the central derivative), did not forget about the initial conditions. The solutions turn out to be correct, but the graphs do not overlap with each other as the accuracy N increases. Why? Is the error somewhere in the code or with what?

Part 2 of the question, is there a nicer way to fill the arrays oX, oY1, oY2? it's not very convenient to copy values ​​from the console and paste them into arrays, maybe you can use some function? How, for example, from data frame to R?

``````import math as m
import matplotlib.pyplot as plt

# y'' + 4y = 4 / sin(2x);    y(pi/4) = 2 ; y'(pi/4) = pi

def f(x):
# Точное реш.
return (m.log(m.fabs(m.sin(2*x))) + 2)*m.sin(2*x) + (-2*x)*m.cos(2*x)

def fn(x):
# неоднородность
return 4/m.sin(2*x)

N = 100
h = 1/N

i = 0

x = m.pi/4

u:float; u1:float; u0: float
u0 = 2; u1 = m.pi*h + 2

while i < N:
u2 = fn(x) * pow(h,2) - 2*u1 * (2*pow(h,2) - 1) - u0    # u2 mean U_(n+1) , где в скобках индексы
x += h                                                  # u1 mean U_n
i += 1                                                  # u0 mean U_(n-1)
# print(i,'U(n)=', u2,'y(x)=', f(x))
# print(u2, ',')
# print(i * h, ',')
print(f(x), ',')

# Берем первых 20 знач. из цикла

oX = [0.05 ,
0.1 ,
0.15000000000000002 ,
0.2 ,
0.25 ,
0.30000000000000004 ,
0.35000000000000003 ,
0.4 ,
0.45 ,
0.5 ,
0.55 ,
0.6000000000000001 ,
0.65 ,
0.7000000000000001 ,
0.75 ,
0.8 ,
0.8500000000000001 ,
0.9 ,
0.9500000000000001 ,
1.0 ]

oY1 = [2.302588469032184 ,
2.302638678216189 ,
2.302791857481596 ,
2.303055985047565 ,
2.3034455133160163 ,
2.303983408305429 ,
2.304704752177307 ,
2.30566306162952 ,
2.306941711028906 ,
2.308675727136845 ,
2.311096626208993 ,
2.3146345129193575 ,
2.320185505045508 ,
2.329971810302939 ,
2.3514233698804583 ,
2.4339567980618853 ,
1.9501171129320132 ,
2.2149755290716815 ,
2.248574790313648 ,
2.261656447015457]

oY2 = [2.1518263016746437 ,
2.292202658780094 ,
2.4198801892121797 ,
2.5338482845690637 ,
2.6333593158228834 ,
2.717959345873653 ,
2.787528235206554 ,
2.8423352460034197 ,
2.8831214252566078 ,
2.9112307270818762 ,
2.9288360448728463 ,
2.939368191384773 ,
2.9484422767097875 ,
2.966297428201235 ,
3.0172108006898744 ,
3.214224781823093 ,
3.249866206813253 ,
3.1649321044435164 ,
3.002896533120906 ,
2.7794652898412173]

plt.plot(oX, oY1, color='green', marker='o', linestyle='solid')
plt.plot(oX, oY2, color='red', marker='o', linestyle='solid')

plt.show()``````

In order to leave comments, you need to log in

V