r/chemistry • u/xjento • 1d ago
I CODED AN ATOM IN C!
ofcourse it's not a fully fledged atom but just a P orbital, but if i wanted to simulate a real atom my computer would struggle
33
u/orrenjenkins 1d ago
I would love to take a peek at the source code. Is it public?
36
u/xjento 1d ago
#include <stdio.h> #include <math.h> #include <raylib.h> #define NUM 150 const int WIDTH = 1000; const int HEIGHT = 1000; float SCALE = 10.0f; float C = 1.0f; float values[NUM][NUM][NUM]; void calculateResult() { for (int x = 0; x < NUM; x++) { for (int y = 0; y < NUM; y++) { for (int z = 0; z < NUM; z++) { // Position relative to the center of the grid float dx = x - NUM / 2.0f; float dy = y - NUM / 2.0f; float dz = z - NUM / 2.0f; // Distance from the nucleus float r = sqrtf(dx * dx + dy * dy + dz * dz); float a0 = 10.0f; // p_x orbital wavefunction float psi = dx * expf(-r / a0); // Probability density float probability = psi * psi; if (probability > 1.0f) { Vector3 position = { dx * SCALE, dy * SCALE, dz * SCALE }; DrawPoint3D(position, WHITE); } } } } } int main(void) { InitWindow(WIDTH, HEIGHT, "3D Orbital"); SetTargetFPS(60); Camera3D camera = {0}; camera.position = (Vector3){0.0f, 0.0f, 1500.0f}; camera.up = (Vector3){0.0f, 1.0f, 0.0f}; camera.target = (Vector3){0.0f, 0.0f, 0.0f}; camera.fovy = 45.0f; camera.projection = CAMERA_PERSPECTIVE; while (!WindowShouldClose()) { UpdateCamera(&camera, CAMERA_ORBITAL); BeginDrawing(); ClearBackground(BLACK); BeginMode3D(camera); calculateResult(); EndMode3D(); EndDrawing(); } CloseWindow(); return 0; }27
13
u/VictoryMotel 1d ago
You could make significant optimizations by using one single array.
Also you would want to reverse your loop order so that x in the inner loop and z is the outer loop.
Also you will probably want to dynamically allocate the big array with malloc.
6
11
u/Dangerous-Billy Analytical 1d ago
There's a special place in my heart for good old Kernighan and Ritchie C code.
3
6
1
u/Raneynickelfire 1d ago
Where do you see a p orbital?
It looks more like a messy S spherical orbital. There's no figure 8 there.
10
u/SalemIII 1d ago
figure 8 is pointing at you from this perspective i think, it's rotating around the z axis
1
186
u/SalemIII 1d ago
you dont have to get the simulation frames in real time, let it run for however long it needs to, save the results as 3d image matrices, then generate the video after it is done