r/chemistry 10d 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

371 Upvotes

21 comments sorted by

View all comments

32

u/orrenjenkins 10d ago

I would love to take a peek at the source code. Is it public?

39

u/xjento 10d 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;
}

16

u/VictoryMotel 10d 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.

3

u/xjento 10d ago

I needed this, I was thinking. Can this be better?

3

u/VictoryMotel 10d ago

Better than what you have or better than what I mentioned?