Создание программы на C ++ для решения уравнения движения с использованием метода Эйлера - PullRequest
0 голосов
/ 26 сентября 2019

Я пытаюсь вычислить временную историю скорости, описываемой уравнением: dV / dt = g - (C_d / m) * V ^ 2 .g = 9,81, m = 1,0 и C_d = 1,5.Для этого мне нужно создать программу на с ++, которая использует явный метод Эйлера для численного решения уравнения.Я пытаюсь найти скорость от t = 0 до t = 1 секунды с тремя различными размерами шага: delta_t = 0,05, 0,1 и 0,2 секунды.И тогда вы должны показать свою процентную ошибку в аналитическом решении, представленном как: V (t) = sqrt ((m * g) / C_d) * tanh (sqrt ((g * C_d) / m) * t). Моя проблема в том, что я не уверен, как перебирать метод Эйлера несколько раз с разными временными интервалами.Пока я решил аналитическое уравнение, но не уверен, куда идти дальше.Если бы кто-нибудь мог помочь направить меня в правильном направлении, это было бы очень ценно.

#include <iomanip>
#include <cmath>
#include <math.h>

using namespace std;

int main() {

    double m = 1.0;     // units in [kg] 
    double g = 9.81;    // units in [m/s^2]
    double C_d = 1.5;   // units in [kg/m]  
    double t;           // units in [s]
    double v;           // units in [m/s]


    cout << "The velocity will be examined from the time t = 0 to t = 1 seconds." << endl;
    cout << "Please select either 0.05, 0.1, or 0.2 to be the time interval:" << endl;
    cin >> t;
    cout << "You have chosen the time interval of: " << t << " seconds." << endl;


    v = sqrt((m * g) / C_d) * tanh(sqrt((g * C_d) / m) * t);

    cout << "The velecity at a time of "<< t << " seconds is equal to: " << v << " m/s." << endl;


    return 0;

} ```

1 Ответ

1 голос
/ 28 сентября 2019

Если вы хотите выполнить итерацию по t с шагом A , вычисляя результат формулы с каждым t , вы должны написать цикл for.

#include <iostream>

int main()
{
    double m = 1.0;     // units in [kg] 
    double g = 9.81;    // units in [m/s^2]
    double C_d = 1.5;   // units in [kg/m]

    std::cout << "The velocity will be examined from the time t = 0 to t = 1 seconds." << std::endl;
    std::cout << "Please select the time interval:" << std::endl;
    std::cout << "1: 0.05" << std::endl;
    std::cout << "2: 0.1" << std::endl;
    std::cout << "3: 0.2" << std::endl;

    double A = 0; // increment in for loop
    int x;
    std::cin >> x;
    switch (x) { // check what the input is equal to
        case 1: A = 0.05; break;
        case 2: A = 0.1; break;
        case 3: A = 0.2; break;
        default: std::cout << "Unknown option!" << std::endl; return 1;
    }
    std::cout << "You have chosen the time interval of: " << A << " seconds." << std::endl;

    std::cout << "Results of V(t):" << std::endl;
    // this initializes a variable t as 0, 
    //and while t is lower than or equal to 1, 
    //it will increment it by a and execute the logic within the scope of the loop.
    for (double t = 0; t < (1 + A); t += A) {
        std::cout << "at t = " << t << ": " << sqrt((m*g) / C_d) * tanh(sqrt((g*C_d) / m) * t) << std::endl;
    }

    return 0;
}

См. https://beginnersbook.com/2017/08/cpp-for-loop/ для получения дополнительной информации.Примечание: я также ввел в код оператор switch, чтобы предотвратить ввод неизвестных значений.https://beginnersbook.com/2017/08/cpp-switch-case/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...