RodrigoDornelles/3bc-lang

implement log10 from scratch

RodrigoDornelles opened this issue · 0 comments

#include <stdio.h>

double log10_custom(double x) {
    if (x <= 0) {
        fprintf(stderr, "Error: log10 of non-positive number is undefined.\n");
        return 0.0;
    }

    union {
        double f;
        unsigned long long i;
    } converter;

    converter.f = x;

    // Extracting the exponent bits
    int exponent = (converter.i >> 52) - 1023;

    // Masking out the exponent bits
    converter.i &= ~(0xFFFULL << 52);
    converter.i |= 1023ULL << 52;

    double y = converter.f - 1.0;
    double z = y * y;

    // Coefficients for the Taylor series
    const double c1 = 0.333333333333333;
    const double c2 = 0.2;
    const double c3 = 0.142857142857143;
    const double c4 = 0.111111111111111;
    const double c5 = 0.0909090909090909;
    const double c6 = 0.0769230769230769;
    const double c7 = 0.0666666666666667;
    const double c8 = 0.0588235294117647;

    // Calculate the logarithm using a simplified Taylor series approximation
    double result = y * (c1 + z * (c2 + z * (c3 + z * (c4 + z * (c5 + z * (c6 + z * (c7 + z * c8)))))));

    // Add the exponent back to the result
    result += exponent;

    return result;
}

int main() {
    double x = 100.0;
    double result = log10_custom(x);
    printf("log10(%lf) = %lf\n", x, result);

    return 0;
}