Home > database >  Wrong results with cosx (custom function) with functions(noobie)
Wrong results with cosx (custom function) with functions(noobie)

Time:12-14

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265

double sin1x(double converted,int i);
double cos1x(double converted,int i);
int main(){
  int r,i = 1;
  double converted,p,results,results1;
  printf("Insert degrees from 0..2π: ");
  scanf("%d", &r);
  if(r < 0 || r > 360)
  {
    printf("NOT ACCEPTABLE DEGREES\n");
    exit(0);
  }
  converted = r * PI / 180;
  printf("Conversion from degrees to rad = %.3f", converted);
  results = sin1x(converted,i);
  results1 = cos1x(converted,i);
  printf("\nsin(%d) = %.3f\n", r, results);
  printf("\nsin(%d) of c = %.3f\n", r,sin(converted));
  printf("\ncos(%d) = %.3f\n", r, results1);
  printf("\ncos(%d) of c = %.3f\n", r,cos(converted));
  return 0;
}

double sin1x(double x, int i)
{
  int j = 3;
  double sinx,numerator = x,pr;
  sinx = numerator;
  do
  {
    pr = numerator;
    numerator = pr * x * x / (j * (j - 1));
    if(i % 2 == 0)
      sinx = sinx   numerator;
    else
    {
      if(i % 2 == 1)
          sinx = sinx - numerator;
    }
      i  ;
      j =2;
    }
  while(fabs(pr - numerator) > 0.000001);
  return sinx;
}

double cos1x(double x, int i)
{
  int j = 2;
  double cosx,numerator = x,pr;
  cosx = numerator;
  do
  {
    pr = numerator;
    numerator = pr * x * x / (j * (j - 1));
    if(i % 2 == 0)
      cosx = cosx   numerator; 
    else
    {
      if(i % 2 == 1)
          cosx = cosx - numerator;
    }
    i  ;
    }
  while(fabs(pr - numerator) > 0.000001);
  return cosx;
}

Hello I try to make a program with cosx and sinx and for some reason I have a problem with cosx. I cannot find any issues with my program but the cos results are wrong.Also I have the sin() and cos() functions to compare the results. I tried changing j or making another variable to factorial but it didn't change anything.

CodePudding user response:

At least these problems:

Wrong initialization

// double cosx,numerator = x,pr;
double cosx,numerator = 1.0,pr;

Missing change to j

// Add to `cos1x()` do loop
j  = 2;

Coarse PI

No reason to not use a more precise value.

// #define PI 3.14159265
#define PI 3.1415926535897932384626433832795

Spelling

Convertion --> Conversion


Candidate simplification

double cos1x_alt(double x) {
  double xx = x * x;
  double term = 1.0;
  double sum = term;
  for (int i = 1; 1.0   term != 1.0; i  = 2) {
    term *= -xx / (i * (i   1));
    sum  = term;
  }
  return sum;
}
  • Related