ctaylor-series

Function that implements Taylor Series in C return the value of the argument


I was experimenting with the Taylor Series expansion for tan(x) in C. I've created a super simple function whose purpose is to return the answer of the expansion (see code below). The issue is that when one invokes it, the answer is the argument of the tangent, i.e. if you call the function tangent as tangent(0.7853981634), which is pi/4 btw, you get that same number 0.7853981634.

#include <stdio.h>

float power(float x, int pow);
float tangent(float x);

void main(){
    float ans;
    ans = tangent(0.7853981634);

    printf("La tangente da %f \n", ans);
}

float tangent(float x){
    return x + 1/3 * (x * x * x) + 2/15 * (x * x * x * x * x);
}

NOTE: I know that there are plenty of things to improve, it's just that I don't know why this code does not work properly.


Solution

  • Save time, enable all compiler warnings.

    Integer division

    1/3 is zero as that is the integer quotient.
    Instead use 1.0f/3.0f * (x * x * x) or the like. @M Oehm