Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modelling a Pendulum in C

This is my code for attempting a while Loop to model a pendulum swing, however the values produced don't seem to help me:

#include <stdio.h>
#include <math.h>
#define PI 3.14159265

main()
{
    float theta = 0;   // initial value for angle
    float omega = 0.2; // initial value for angular speed
    float time = 0;    // initial time
    float dt = 0.01;   // time step

    while (theta < 2 * PI && -2*PI) {
        time = time + dt;
        theta = theta + omega*dt;

        printf("theta=%i, omega=%i, time=%i, and dt=%i\n", theta, omega, time, dt);
    }
    system("PAUSE");
}

How can I modify this to be more helpful? The while condition I have to use is that it should stop when the pendulum has made one revelation either forwards or backwards (-2PI or 2PI). I need to use the formula 'omega=omega-(g/l)dtsin(theta)' and NOT make the assumption that theta approximately equals sin(theta).

like image 602
Josh Mulkeen Avatar asked Dec 15 '22 09:12

Josh Mulkeen


2 Answers

  1. while(theta <2*PI&&-2*PI)

    In c if we want to combine multiple expressions we can combine them using logical operators as

    while((theta < 2 * PI) && (theta > -2 * PI))  
    

    PS- I am no physics expert. Change conditions as per your requirement

like image 171
rootkea Avatar answered Dec 31 '22 12:12

rootkea


There are some problem in this code :

  1. According to the standard you shouldn't use

    main()
    

    But either

    1. int main()
    2. int main(void)
    3. int main(int argc, char *argv[])

    Also don't forget

    return 0;
    

    Sample program :

    #include <stdio.h>
    
    int main(void) {       
        /* Do stuff */        
        return 0;    
    }
    

    If you wish to read more information about that, click here.

  2. As LutzL pointed out you should use M_PI instead of your definition of PI. Just #include <math.h>

    That's how you would print the value for example :

    printf("\nValue of M_PI is %f\n\n", M_PI);
    

    Read more here.

  3. As pointed out by rootkea :

    In c if we want to combine multiple expressions we can combine them using logical operators as

    while((theta < 2 * PI) && (theta > -2 * PI))

  4. If you want greater precision (I think that this is the case) you should use double instead of float.

  5. You are trying to print float variables with the "%i" format specifier. That's wrong, "%i" is used to print int signed integer and using the wrong specifier invokes undefined behavior. You should use "%f" to print float or double signed decimal.

Have a read about printf format specifiers here.

like image 30
Claudio Cortese Avatar answered Dec 31 '22 13:12

Claudio Cortese