#include <stdio.h>
#include <math.h>
#define PI 3.141592653589793
#define I0 1.0 // Max intensity
#define SLIT_WIDTH 0.001 // Slit width in meters
#define WAVELENGTH 500e-9 // Wavelength in meters (500 nm)
void write_data_to_file(const char *filename) {
FILE
*fp
= fopen(filename
, "w"); if (!fp) {
perror("Failed to open file"); return;
}
for (double theta = -0.1; theta <= 0.1; theta += 0.001) {
double beta
= (PI
* SLIT_WIDTH
* sin(theta
)) / WAVELENGTH
; double intensity
= I0
* pow(sin(beta
) / beta
, 2); fprintf(fp
, "%f %f\n", beta
, intensity
); }
}
int main() {
const char *filename = "intensity_vs_beta.txt";
write_data_to_file(filename);
// Plotting using GNUplot
FILE *gnuplotPipe = popen("gnuplot -persistent", "w");
if (gnuplotPipe) {
fprintf(gnuplotPipe
, "set title 'Single Slit Diffraction: Intensity vs. Beta'\n"); fprintf(gnuplotPipe
, "set xlabel 'Beta'\n"); fprintf(gnuplotPipe
, "set ylabel 'Intensity'\n"); fprintf(gnuplotPipe
, "plot '%s' using 1:2 with lines title 'Intensity'\n", filename
); pclose(gnuplotPipe);
} else {
fprintf(stderr
, "Could not open GNUplot.\n"); }
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxtYXRoLmg+CgojZGVmaW5lIFBJIDMuMTQxNTkyNjUzNTg5NzkzCiNkZWZpbmUgSTAgMS4wIC8vIE1heCBpbnRlbnNpdHkKI2RlZmluZSBTTElUX1dJRFRIIDAuMDAxIC8vIFNsaXQgd2lkdGggaW4gbWV0ZXJzCiNkZWZpbmUgV0FWRUxFTkdUSCA1MDBlLTkgLy8gV2F2ZWxlbmd0aCBpbiBtZXRlcnMgKDUwMCBubSkKCnZvaWQgd3JpdGVfZGF0YV90b19maWxlKGNvbnN0IGNoYXIgKmZpbGVuYW1lKSB7CiAgICBGSUxFICpmcCA9IGZvcGVuKGZpbGVuYW1lLCAidyIpOwogICAgaWYgKCFmcCkgewogICAgICAgIHBlcnJvcigiRmFpbGVkIHRv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