41223108 cp2023

  • Home
    • SMap
    • reveal
    • blog
  • About
  • 倉儲維護
    • s.cycu.org維護
    • windows維護
  • weekly progress
    • w1~4
    • w5
    • w6
    • w7
    • w9
    • w12
      • helloworld
      • GD繪圖程式1
    • W13
    • w15
  • ANSIC
    • 1.
    • 2.
    • 3.
    • 4.
    • 5.
    • 6.
    • 7.
    • 8.
    • 9.
    • 10.
  • NOTE
    • ssh
    • puttygen
  • 國旗練習
    • Thai
    • Laos
    • Bangladesh
    • vietnam
    • Italian
    • Russia
    • Belgium
    • Ukraine
    • Korea
  • 課程評分
  • Brython
  • setup
  • C_lib
  • replit
  • MSD
  • Final
replit << Previous Next >> Final

MSD

Mass-Spring-Damper 是一個典型的物理模型, 由質量-彈簧-阻尼器等三個元件組成, 若將彈簧其拉力與變形量成正比, 若假設阻尼器的阻力大小則與其受力方向的速度成正比, 根據牛頓運動定律, 就可以從物理模型的自由體圖導入系統的運動方程式. 接下來就要利用計算機程式, 解此一系統的微分方程式.

euler_gnuplot_msd_ex1.c 程式內容:

// 包含標準輸出入程式庫的標頭文件
#include <stdio.h>
  
// 主函式
int main() {
    // Open a file to write displacement and velocity data
    FILE *outputFile = fopen("motion_data.txt", "w");
    if (!outputFile) {
        fprintf(stderr, "Failed to create data file.\n");
        return 1;
    }
  
    // Simulate motion for 10 seconds and calculate displacement and velocity, while writing data to the file
    double x = 0.2;  // Initial displacement
    double v = 0.0;  // Initial velocity
    double dt = 0.01; // Time step
    double t = 0.0;  // Time
  
    while (t <= 10.0) {
        double acceleration = (-10.0 * x - 0.5 * v) / 1.0; // Modified system parameters here
        v += acceleration * dt;
        x += v * dt;
  
        fprintf(outputFile, "%lf %lf %lf\n", t, x, v);
  
        t += dt;
    }
  
    // Close the data file
    fclose(outputFile);
  
    // Start a Gnuplot process using popen
    FILE *gnuplotPipe = popen("gnuplot -persistent", "w");
    if (!gnuplotPipe) {
        fprintf(stderr, "Failed to start Gnuplot.\n");
        return 1;
    }
  
    // Use Gnuplot plotting commands, specify font and output as PNG
    fprintf(gnuplotPipe, "set terminal pngcairo enhanced font 'default,10' size 800,400\n");
    fprintf(gnuplotPipe, "set output './../images/motion_plot.png'\n");
    fprintf(gnuplotPipe, "set title 'Displacement and Velocity vs. Time'\n");
    fprintf(gnuplotPipe, "set xlabel 'Time (s)'\n");
    fprintf(gnuplotPipe, "set ylabel 'Displacement (m)'\n");
    fprintf(gnuplotPipe, "plot 'motion_data.txt' using 1:2 with lines lw 2 title 'Displacement', \
                             'motion_data.txt' using 1:3 with lines lw 2 title 'Velocity'\n");
  
    // Close the Gnuplot process
    fprintf(gnuplotPipe, "exit\n");
    pclose(gnuplotPipe);
  
    return 0;
}


replit << Previous Next >> Final

Copyright © All rights reserved | This template is made with by Colorlib