Skip to content

Instantly share code, notes, and snippets.

@not7cd
Last active May 30, 2018 14:26
Show Gist options
  • Save not7cd/905e55cf01add1d77cd59c82c32bf327 to your computer and use it in GitHub Desktop.
Save not7cd/905e55cf01add1d77cd59c82c32bf327 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
int random(int min, int max)
{
int tmp;
if (max>=min)
max-= min;
else
{
tmp= min - max;
min= max;
max= tmp;
}
return max ? (rand() % max + min) : min;
}
struct vector {
float x;
};
struct particle {
float mass;
struct vector position;
struct vector velocity;
};
float vector_len(struct vector * v) {
return sqrt(pow(v->x, 2));
}
float particle_momentum(struct particle * ptr) {
return ptr->mass * vector_len(&ptr->velocity);
}
float particle_energy(struct particle * ptr) {
return 0.5* ptr->mass * pow(vector_len(&ptr->velocity), 2);
}
void print_particle(struct particle * ptr) {
printf("\nmass: %f\n", ptr->mass);
printf("speed: %f\n", vector_len(&ptr->velocity));
printf("position: %f\n", ptr->position.x);
printf("momentum: %f\n", particle_momentum(ptr));
printf("energy: %f\n", particle_energy(ptr));
}
int main() {
struct particle * particles;
int p_len;
srand(time(NULL));
scanf("%i", & p_len);
particles = calloc(p_len, sizeof(struct particle));
int i;
double total_e = 0, total_m = 0;
for (i = 0; i<p_len; i++) {
particles[i].mass = random(0, 999);
particles[i].velocity.x = random(-100, 100);
particles[i].position.x = random(-100, 100);
print_particle(&particles[i]);
total_m += particle_momentum(&particles[i]);
total_e += particle_energy(&particles[i]);
}
printf("total momentum: %f\n", total_m);
printf("total energy: %f\n", total_e);
free(particles);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment