Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a sine function in c

Tags:

c

math

I know there is a sin function in math.h but I want to make that function on my own, just for fun. I have created sin function based on Macluarin expansion of the sine function. enter image description here

I wrote a power function and a factorial function, they work correctly from main, but they are not working in the sin function.

Here is my code:

int main()
{
    int i;
    double y;
    printf("\n\nPlease enter a value to find corresponding sin value\n");
    scanf("%d",&i);
    y=sin(i);
    printf("\nYour value is\n %f",y);
    return 0;
}
    
double sin(int z)
{
    int i=1;
    double value,val2,val3,sum=0;
    for(i=1;i<33;i+=2)
    {
        val2=power(z,i);
        val3=factorial(i);
        value=val2/val3;
        if(((i-1)/2)%2!=0){
            sum=sum-value;    //((power(x,i))/factorial(i));
        }else
        {
            sum=sum+value;
        }
    }
    printf("\n%f\n",sum);
    return sum;
}

int factorial(int x)
{
    int i,sum=1;
    for(i=1;i<=x;i++)
    {
        sum = sum*i;
    }
    return sum;
}

int power(int x,int y)
{
    unsigned long long int i,sum=1;
    for(i=1;i<=y;i++)
    {
        sum=sum*x;
    }
    return sum;
}
like image 971
Kumar Avatar asked Oct 21 '25 13:10

Kumar


2 Answers

The formula expects values in radians but you're using integers so I'm assuming you give it degrees. That will make the formula give wrong values.

Also you use ints as return values from factorial() and power() which will cause overflows. If you have 32bit machine even giving 2 to your formula will overflow since int can only go up to 2^31-1 and your trying to get 2^33.

Also if your compiler doesn't complain that you're returning an unsigned long long int from a function that has int as a return type please increase the warning level.

like image 142
Sami Kuhmonen Avatar answered Oct 23 '25 04:10

Sami Kuhmonen


int factorial() overflows quite quickly. 13! doesn't fit into 32-bit integer. 21! doesn't fit into 64-bit integer.

int power() seems totally off. Why do you expect an argument x to be int? BTW, it also overflows quickly.

The (almost) right way to compute McLauren series is to express the next term from the previous one:

    term = (-1) * term * (x*x) / ((n+1)*(n+2));
    sum += term;
    n += 2;

It shall work, but may lead to numerical instabilities with large x. A Horner schedule is an ultimate answer.

like image 24
user58697 Avatar answered Oct 23 '25 04:10

user58697



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!