#define MAX_ITERATIONS 100000
#define PI 3.14159265359
#include <stdio.h>
#include <stdlib.h>
#include "pico/float.h"
#include "pico/double.h"
/**
* @brief Print pi to the console
*
* @return int Application return code (zero for success).
*/
/**
* @brief Computes pi using the Wallis Product using single-precision
*
* @param n The amount of terms to sum
*
* @return float pi (calculates using Wallis Product
*/
float wallis_product_float(int n) {
float pi = 1.0;
for (int i = 1; i <= n; i++) {
float two_n = 2.0 * (float) i;
pi *= (two_n / (two_n - 1.0)) * (two_n / (two_n + 1.0));
}
return pi * 2.0;
}
/**
* @brief Computes pi using the Wallis Product using double-precision
*
* @param n The amount of terms to sum
*
* @return double pi (calculates using Wallis Product
*/
double wallis_product_double(int n) {
double pi = 1.0;
for (int i = 1; i <= n; i++) {
double two_n = 2.0 * (double) i;
pi *= (two_n / (two_n - 1.0)) * (two_n / (two_n + 1.0));
}
return pi * 2.0;
}
int main() {
stdio_init_all();
// Calculate pi using Wallis Product using single-precision
float pi_f = wallis_product_float(MAX_ITERATIONS);
// Calculate approximation error
float error_f = pi_f - PI;
// Get absolute value of error
if (error_f < 0.0) {
error_f = - error_f;
}
// Calculate pi using Wallis Product using double-precision
double pi_d = wallis_product_double(MAX_ITERATIONS);
// Calculate approximation error
double error_d = pi_d - PI;
// Get absolute value of error
if (error_d < 0.0) {
error_d = - error_d;
}
while (true) {
// Print values and approximation errors to console.
printf("Single-Precision: \nCalculated Value: %f \nApproximation Error: %f \n \nDouble-Precision: \nCalculated Value: %lf \nApproximation Error: %lf \n---------------------- \n", pi_f, error_f, pi_d, error_d);
sleep_ms(1000);
}
// Returning zero indicates everything went okay.
return 0;
}