Home > Software engineering >  Errors in a custom sine function
Errors in a custom sine function

Time:10-27

I am prototyping a sine function for an extremely simple programing language (Namely, limitations being only signed int variable types, and only operations between variables). However, there seems to be an error every radian or so with a given value for "s" that is greater than or equal to 0.9. This error seems to be an offset of 1, and then -1 for a small range (This is all within the same error - the 1 and then -1 is consecutive without any correct output values between). This error didn't show up on a desmos graph with the same function (The error in the desmos graph is a small jump between the approximated values). I did assume that it would be a problem with the approximation for pi and tau, but it seemed otherwise given a larger value for "s". My code is as follows:

#include <iostream>

int sin(int x, int s1, int s2)
{
  int p = x;
  int pi = 314159;
  int k = 1000;
  int tau = 628318;
  int six = 6;
  int oneHundredTwenty = 120;
  int fiveThousandFourty = 5040;
  int ans;
  int a3;
  int a5;
  int a7;
  float s = 0.9;

  pi *= s;
  pi /= 100;
  tau *= s;
  tau /= 100;
  k *= s;

  p %= tau;
  p -= pi;

  a3 = p;
  a5 = p;
  a7 = p;

  ans = p;


  a3 *= p;
  a3 /= k;
  a3 *= p;
  a3 /= k;
  a3 /= six;

  a5 *= p;
  a5 /= k;
  a5 *= p;
  a5 /= k;
  a5 *= p;
  a5 /= k; 
  a5 *= p;
  a5 /= k;
  a5 /= oneHundredTwenty;

  a7 *= p;
  a7 /= k;
  a7 *= p;
  a7 /= k;
  a7 *= p;
  a7 /= k;
  a7 *= p;
  a7 /= k;
  a7 *= p;
  a7 /= k;
  a7 *= p;
  a7 /= k;
  a7 /= fiveThousandFourty;

  ans -= a3;
  ans  = a5;
  ans -= a7;

  return 30   ans / 33;

}

int main()
{

  for(int i = 0; i < 1000; i   )
  {
    for(int j = 0; j < sin(i * 100, 1, 1); j   )
    {
      std::cout << "#";
    }
    std::cout << "\n";
  }
  return 0;
}

CodePudding user response:

Your a7 variable is overflowing.

In your code, the value of a7 gets as large as 2,431,570,725 and as small as -2,443,460,910. Your int range is probably almost, but not quite, that large. A typical value of INT_MAX is 2,147,483,647.

Change it to a long or long long or something like that.

  •  Tags:  
  • c
  • Related