#define WOKWI // Uncomment if running on Wokwi RP2040 emulator
#define PI 3.14159265359
#define MAX_ITERATIONS 100000
#include <stdio.h>
#include <stdlib.h>
/**
* @brief Function to calculate pi using the Wallis product, using single-precision floating-point
* representation
*
* This function estimates the value of PI using the Wallis algorithm. It iteratively computes
* the product of fractions based on the Wallis formula and uses this to optimize Pi. This
* function uses single-precision floating-point representation
*
* @return the calculated value of PI
*
*/
float single_precision() {
float pi = 1.0;
for (int i = 1; i <= MAX_ITERATIONS; i++) {
float numerator = 4.0 * i * i;
float denominator = numerator - 1;
pi = pi * (numerator / denominator);
}
pi = pi * 2.0;
return pi;
}
/**
* @brief Function to calculate pi using the Wallis product, using double-precision floating-point
* representation
*
* This function estimates the value of PI using the Wallis algorithm. It iteratively computes
* the product of fractions based on the Wallis formula and uses this to optimize Pi. This
* function uses double- precision floating-point representation
*
* @return the calculated value of PI
*
*/
double double_precision() {
double pi = 1.0;
for (int i = 1; i <= MAX_ITERATIONS; i++) {
double numerator = 4.0 * i * i;
double denominator = numerator - 1;
pi = pi * (numerator / denominator);
}
pi = pi * 2.0;
return pi;
}
/**
* @brief Main function that outputs the values to the serial monitor
*
* This is the main function of the program. It calls the Wallis functions and calculates
* the approximate error between these results and the defined PI. It submits these results
* to the serial monitor.
*
* @return always returns 0.
*/
int main() {
float singlePI = single_precision();
float comparedSingle = PI - singlePI;
double doublePI = double_precision();
double comparedDouble = PI - doublePI;
// Print a console message to inform user what's going on.
printf("Calculated value of PI using single-precision = %f\n", singlePI);
printf("Approximation error = %f\n", comparedSingle);
printf("Calculated value of PI using double-precision = %lf\n", doublePI);
printf("Approximation error = %lf\n", comparedDouble);
// Returning zero indicates everything went okay.
return 0;
}