簡體   English   中英

我是否在 C++ 中正確實現了歐拉方法?

[英]Am I implementing Euler's Method correctly in C++?

我被要求編寫一個 C 或 C++ 程序來解決給定的微分方程

這必須使用歐拉方法在數值上實現。 用戶應該能夠在程序開始時輸入速度 (v)、x(0) 的初始值和最終時間 (T)。它還應該繪制時間 0 <t < T 的數值解。

我覺得我的程序運行良好,但我在方程方面無法正確實施歐拉方法。 這是我創建的程序。 任何反饋/建議將不勝感激。 如果您需要更多信息,請告訴我。

#include <iostream>
#include <string>
#include <stdio.h>
#include <unistd.h>
#include <math.h>
using namespace std;
#include <stdlib.h>
#include <stdarg.h>
#include <assert.h>
#include <array>
#include "gnuplot.cxx"

int main()
{
    //establishing  values
    double v, x0, T, dt, number_steps;
    const int max_number_steps = 100000;
    int i=0;
    
    //establishing numverical arrays
    double value_t [max_number_steps];
    double approx_x [max_number_steps];
 
   //Allow users to input variables
    cout<<"Enter Initial Condition"<< endl;
    cout<<"Velocity(v) = ";
    cin>> v;
    cout<<"x0 = ";
    cin >> x0;
    cout<<"Final time(T) = ";
    cin >> T;   
    cout << "number steps = ";
    cin >> number_steps;
    
    //Establishing stepside and assigning arrays
    dt = T/number_steps;
    value_t[0]= 0.0;
    approx_x[0] = x0;

    //for loop which should implement Euler's Method 
    for ( i= 0; i < number_steps; i++)
    {
        value_t [i+1] = dt*(i+1);
        approx_x[i+1] = approx_x[i+1] + dt*v;

    }
    
    //Graph the plot via gnuplot
     gnuplot_one_function("Velocity", "linespoints", "Time(t)", "Position(x)", value_t, approx_x, number_steps);

    return 0;
}

除了與干凈代碼相關的問題外,您還有一個錯誤:

approx_x[i+1] = approx_x[i+1] + dt*v;

歐拉法從第 x_{i} 個元素計算出第 x_{i+1} 個元素,將微分方程的右手邊乘以 step 如下:

approx_x[i+1] = approx_x[i] + dt*v;  // where approx_x[0] = x_0;

您對 Euler 方法概念存在根本性錯誤。


my_aprox[i + 1]  = my_aprox[i] + dt*v

請記住,要計算新的近似值,您必須具有“先驗”初始值,下一個近似值將是下一個初始值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM