Question

I need to approximate the sine function without internal libraries. I used Taylor series in 0 to solve this, but my program works for some values, but for others awful results. The program gets x value, unit (degrees or radians) and how many words we want use for the approximation. For values like

1 rad, 5 words results are ok: sin(1 pi) = 0.833333 Difference: 0.00813765;

sin(0.5 pi) = 0.479167 Difference: 0.000258872

But for values like 125.6 rad it returns 2.60145e+008 and C++ sin() function gives -0.0636631, so the result is completely unreal.

Also it doesn't work for values in degrees although I convert degrees on radians. E.g. sin(4.71239 pi) = 6.63667 and real result should be -1. I completely don't have any idea why it doesn't work properly, could anyone tell me what could cause these problems?

#include <iostream>
#include <math.h>

#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

using namespace std;

double degConverter(double);
void approximate(double, int, int);
int derivative(int);
double compareWithNorm(double, double);
double inline reductionFormula(double);

double inline degConverter(double x)
{
    return x / 180.0; //x * M_PI / 180.0    <-- the expression in comment gives wrong results in all situations?
}

void approximate(double x, int unit, int words)
{
    double result = 0;
    double xVal = 0;
    int factorial = 1;


    if (unit == 1)
    {
        xVal = x;
    }
    else if (unit == 0)
    {
        xVal = degConverter(x);
        x = xVal;
    }

    if (words > 1)
    {
        for (int i = 1; i < words; i++)
        {
            switch (i % 4)
            {
                case 1:
                    result += xVal / (double)factorial;
                break;

                case 3:
                    result -= xVal / (double)factorial;
                break;

            }
            xVal *= x;
            silnia *= i + 1;
        }
    }

    //Comparing with sin() function from math.h lib
    cout << "Difference between sin C++ and Taylor: " << compareWithNorm(x, result) << endl;
}



double compareWithNorm(double x, double result)
{
    double diff = 0;
    double pattern = sin(x);
    diff = pattern - result;
    if (diff < 0)
        diff *= -1;

    return diff;

}


double inline reductionFormula(double x)
{

    if (x > 2)
    {
        x = fmod(x, 2.0);
    }
    return x;
}

int main()
{
    double x;
    int unit = 1;
    int words = 1;

    cout << "Type x [degrees / rad]: ";
    cin >> x;
    cout << "\nType unit [deg = 0 / rad = 1]: ";
    cin >> unit;
    cout << "\nHow many words?: ";
    cin >> words;
    cout << endl;

    approximate(x, unit, words);

    return 0;
}

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with cs.stackexchange
scroll top