Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement log10 from scratch #407

Open
RodrigoDornelles opened this issue Jun 11, 2023 · 0 comments
Open

implement log10 from scratch #407

RodrigoDornelles opened this issue Jun 11, 2023 · 0 comments
Assignees

Comments

@RodrigoDornelles
Copy link
Owner

#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;
}
@RodrigoDornelles RodrigoDornelles self-assigned this Jun 11, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant