How to create a Single Vector having 2 Dimensions?

不羁的心 提交于 2021-01-28 12:09:28

问题


I have used the Equation of Motion (Newtons Law) for a simple spring and mass scenario incorporating it into the given 2nd ODE equation y" + (k/m)x = 0; y(0) = 3; y'(0) = 0.

I have then been able to run a code that calculates and compares the Exact Solution with the Runge-Kutta Method Solution.

It works fine...however, I have recently been asked not to separate my values of 'x' and 'v', but use a single vector 'x' that has two dimensions ( i.e. 'x' and 'v' can be handled by x(1) and x(2) ).

MY CODE:

# Given is y" + (k/m)x = 0; y(0) = 3; y'(0) = 0

# Parameters
h = 0.01;  #Step Size
t = 100.0;  #Time(sec)
k = 1;
m = 1;
x0 = 3;
v0 = 0;

# Exact Analytical Solution
te = np.arange(0, t ,h);
N = len(te);
w = (k / m) ** 0.5;
x_exact = x0 * np.cos(w * te);
v_exact = -x0 * w * np.sin(w * te);

# Runge-kutta Method
x = np.empty(N);
v = np.empty(N);
x[0] = x0;
v[0] = v0;

def f1 (t, x, v):
    x = v
    return x
def f2 (t, x, v):
    v = -(k / m) * x
    return v

for i in range(N - 1):    #MAIN LOOP
    K1x = f1(te[i], x[i], v[i])
    K1v = f2(te[i], x[i], v[i])

    K2x = f1(te[i] + h / 2, x[i] + h * K1x / 2, v[i] + h * K1v / 2)
    K2v = f2(te[i] + h / 2, x[i] + h * K1x / 2, v[i] + h * K1v / 2)

    K3x = f1(te[i] + h / 2, x[i] + h * K2x / 2, v[i] + h * K2v / 2)
    K3v = f2(te[i] + h / 2, x[i] + h * K2x / 2, v[i] + h * K2v / 2)

    K4x = f1(te[i] + h, x[i] + h * K3x, v[i] + h * K3v)
    K4v = f2(te[i] + h, x[i] + h * K3x, v[i] + h * K3v)

    x[i + 1] = x[i] + h / 6 * (K1x + 2 * K2x + 2 * K3x + K4x)
    v[i + 1] = v[i] + h / 6 * (K1v + 2 * K2v + 2 * K3v + K4v)

Can anyone help me understand how I can create this single vector having 2 dimensions, and how to fix my code up please?


回答1:


You can use np.array() function, here is an example of what you're trying to do:

x = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])



回答2:


Unsure of your exact expectations of what you are wanting besides just having a 2 lists inside a single list. Though I do hope this link will help answer your issue. https://www.tutorialspoint.com/python_data_structure/python_2darray.htm?



来源:https://stackoverflow.com/questions/64102275/how-to-create-a-single-vector-having-2-dimensions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!