Skip to content

Instantly share code, notes, and snippets.

@ram-nad
Created March 8, 2020 11:48
Show Gist options
  • Save ram-nad/56b2ba66683239b88832518aa5babd86 to your computer and use it in GitHub Desktop.
Save ram-nad/56b2ba66683239b88832518aa5babd86 to your computer and use it in GitHub Desktop.
#include <cmath>
#include <iomanip>
#include <iostream>
#include <utility>
double sqrt(double a) {
double b = a;
double diff = a - (b * b);
while (diff >= 1e-15 || diff <= -1e-15) {
b = (b + a / b) / 2;
diff = a - (b * b);
}
return b;
}
double calculatePI() {
double a = sqrt(2);
double b = 0;
double p = 2 + a;
for (int i = 0; i < 6; i++) {
double d = sqrt(a);
b = (1 + b) * d / (a + b);
a = (d + (1 / d)) / 2;
p = (1 + a) * (p * b) / (1 + b);
}
return p;
}
double pi = calculatePI();
using pdd = std::pair<double, double>;
pdd AGM_step(const pdd& a) {
pdd b;
b.first = (a.first + a.second) / 2;
b.second = sqrt(a.first * a.second);
return b;
}
double log_g(double a) {
pdd x = std::make_pair(1.0, 4 / a);
for (int i = 0; i < 6; i++) {
x = AGM_step(x);
}
return (pi / 2) / x.first
}
double log(double a) {
if (a >= 1e8) {
return log_g(a);
} else {
double m = 0;
double pow_m = 1;
while (a * pow_m < 1e8) {
m++;
pow_m *= 10.0;
}
return log_g(a * pow_m) - (m * M_LN10);
}
}
int main() {
std::cout << std::setprecision(15);
std::cout << "Built In: " << M_SQRT2 << std::endl;
std::cout << "Calculated: " << sqrt(2) << std::endl;
std::cout << "Built In: " << M_SQRT1_2 << std::endl;
std::cout << "Calculated: " << sqrt(0.5) << std::endl;
std::cout << "Built In: " << M_PI << std::endl;
std::cout << "Calculated: " << pi << std::endl;
std::cout << "Built In: " << 9 * M_LN10 << std::endl;
std::cout << "Calculated: " << log(1e9) << std::endl;
std::cout << "Built In: " << M_LN10 << std::endl;
std::cout << "Calculated: " << log(10) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment