【问题标题】:Am I implementing Euler's Method correctly in C++?我是否在 C++ 中正确实现了欧拉方法?
【发布时间】:2021-12-11 01:15:21
【问题描述】:

我被要求写一个C或C++程序来解决the given differential equation

这必须使用欧拉方法在数值上实现。用户应该能够在程序开始时输入速度 (v)、x(0) 的初始值和最终时间 (T)。它还应该绘制时间 0

我觉得我的程序运行良好,但在方程方面正确实施欧拉方法时遇到了麻烦。这是我创建的程序。任何反馈/建议将不胜感激。如果您需要更多信息,请告诉我。

#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;
}

【问题讨论】:

  • 是的,需要更多信息。你的程序有什么问题吗?如果不是,这更适合codereview。如果是,请添加minimal reproducible example - 删除绘图并添加所需和获得的输出。
  • 请不要使用不相关的语言进行标记。
  • 没有 C/C++ 语言,它们非常不同,每个新版本更是如此。这似乎是 C++。
  • 你有很多不必要的包含。
  • @Arkku • 我正在研究一种我称之为C/C++ 语言的语言。这将有助于所有提出有关 C/C++ 语言问题的人。它基于 OCaml。

标签: c++ numerical-methods ode


【解决方案1】:

你对欧拉方法概念有一个根本性的错误。


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

请记住,要计算新的近似值,您必须“先验”初始值,而下一个近似值将是下一个初始值。

【讨论】:

    【解决方案2】:

    除了与干净代码相关的问题外,这里还有一个错误:

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

    Euler 方法从第 x_{i} 个元素计算第 x_{i+1} 个元素,并将微分方程的右手边乘以 step 这样:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-02
      • 2012-01-08
      • 2016-06-09
      • 2014-04-26
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      相关资源
      最近更新 更多