模拟行进正弦波

计算科学 C++ 波传播
2021-12-29 13:12:42

我正在尝试制作正弦行波(幅度与位置)的动画,这里的任何人都会碰巧知道该怎么做吗?

2个回答

一个非常简单的例子

#include <iostream>
#include <cmath> // sin
#include <fstream> //ofstream
#include <sstream> //stringstream
#include <string> //string
#include <cstring> //c_str

#define PI 3.14159265

// Modifies the elements in an array to five an evenly spaced number of points 
// Along the specified interval (from b to a)
void linspace(double a, double b, double c, double * array){
        double delta =(b-a)/(c-1);
        for (int i=0; i<c; ++i){
                array[i]= i*delta;
       }
}


int main(int argc, char * argv[]){
       double c=1.;
       double x=0;

       double u[90];
       for (int i=0; i<90; ++i){ u[i] = 0.; } // Initalize array
       double a=0., b=10.;
       linspace(a, b, 90, u);

std::string file ="datsin";  // Output file name
        for (int i=0; i<90; ++i){
               std::ostringstream oss;
               oss << "datsin" << i;
               std::ofstream out(oss.str().c_str());
               for (int t=0; t<=360; ++t){
                       out << t<<'\t'<< sin(u[i]+(t*PI/180)) <<'\n';
               }
               out.close();
       }
}

这将在以“datsinX”开头的一系列文件中输出每个时刻波浪的空间坐标,在这种情况下,X 将是从 0 到 89 的数字。为了现在制作动画,可以使用以下 gnuplot 脚本:

set terminal gif animate delay 10
set output "animate.gif"
set yrange[-1:1]
set xrange[0:400]
n=90  
i=0
load "plot.gnuplot"
set output 

在这种情况下,它将依次调用脚本“plot.gnuplot”

plot 'datsin'.i w p ps 2 title sprintf("t=%i",i) 
i=i+1
if (i < n) reread
pause 3

并将生成一个名为“animation.gif”的 gif

数学中:

Animate[Plot[Sin[x + t], {x, -5, 5}], {t, 0, 10}]