My_sine: what is wrong with my function? [closed] - c

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Okay, so I have tried everything I could think of and haven't been able to figure out how to get this program working. I have tested all the functions used in the main, but included them anyway just in case there is some bug in them. More than likely though, I believe my mistake is in the main.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265359
double int_power(double x, int e);
int main()
{
int my_factorial(int n);
double my_sine_taylor(double x);
double my_sine(double x);
double mod_two_pi(double x);
double get_double(void);
void safeGetString(char arr[], int limit)
char arr[255];
double x,y,ans;
printf("Enter a number: ");
safeGetString(arr[255],255);
my_sine(mod_two_pi(get_double()));
printf("The sine is %f \n", ans);
return 0;
}
/*
int_power should compute x^e, where x is a double and e is an integer.
*/
double int_power(double x, int e)
{
int i = 0;
double ans = 1;
while(i <= e)
{
ans = ans*x;
i++;
}
return ans;
}
/*
my_factorial will find the factorial of n
*/
int my_factorial(int n)
{
int i = n;
int ans = 1;
while(i > 0)
{
ans = ans*i;
i = i-1;
}
return ans;
}
/*
my_sine_taylor computes the approxmiation
of sin(x) using the taylor series up through x^11/11!
*/
double my_sine_taylor(double x)
{
return x - int_power(x,3)/my_factorial(3) + int_power(x,5)/my_factorial(5) -
int_power(x,7)/my_factorial(7) + int_power(x,9)/my_factorial(9) -
int_power(x,11)/my_factorial(11);
}
/*
my_sine(x) should return a very good approximation of sin(x).
It should first reduce x mod 2pi and then map the result into the
upper right quadrant (where the taylor approximation is quite accurate).
Finally, it should use my_sine_taylor to compute the answer.
*/
double my_sine(double x)
{
double ans;
if (x >= 0 && x <= PI/2){
ans = my_sine_taylor(x);
} else if (x > PI/2 && x <= PI){
x=PI-x;
ans = my_sine_taylor(x);
} else if (x > PI && x <= 3*(PI/2)){
x = x-PI;
ans = -(my_sine_taylor(x));
} else {
x=2*PI-x;
ans = -(my_sine_taylor(x));
}
}
/*
mod_two_pi(x) should return the remainder when x
is divided by 2*pi. This reduces values like
17pi/2 down to pi/2
*/
double mod_two_pi(double x)
{
int y;
y = floor(x/(2*PI));
x = x - 2*PI*y;
return x;
}
/*
get_double and safeGetString are used to get floating point
input from the user
*/
double get_double(void)
{
double x;
char arr[255];
x=atof(arr);
}
void safeGetString(char arr[], int limit)
{
int c, i;
i = 0;
c = getchar();
while (c != '\n'){
if (i < limit -1){
arr[i] = c;
i++;
}
c = getchar();
}
arr[i] = '\0';
}

oh my... where to begin?
Let's see...
You have this function:
double get_double(void)
{
double x;
char arr[255];
x=atof(arr);
}
Which you call like this:
my_sine(mod_two_pi(get_double()));
So you're not sending it anything, but you're expecting to get some meaningful value. Basically, arr[255] is not initialized, so it holds garbage. You're taking this garbage and converting it to a float with atof, but that doesn't do anything.
If I had to guess, I'd say that this is what's really breaking your program. The rest of what I wrote below is just commentary.
For some reason, you're declaring all of these functions inside your main. I don't think this should break anything, but it sure is bad coding style.
my_sine_taylor calculates using a 6-element taylor approximation of the sine. Are you sure you need that accuracy? 11! is pretty large, and certain numbers to the 11th power can also be pretty large. You may be introducing unnecessary rounding or overflow errors with this.

Related

Calculating $\sqrt[3]{x}$ with Babylonian method

Consider my attempt to implement the Babylonian method in C:
int sqrt3(int x) {
double abs_err = 1.0;
double xold = x;
double xnew = 0;
while(abs_err > 1e-8) {
xnew = (2 * xold + x/(xold* xold))/3;
abs_err= xnew-xold;
if (abs_err < 0) abs_err = -abs_err;
xold=xnew;
}
return xnew;
}
int main() {
int a;
scanf("%d", &a);
printf(" Result is: %f",sqrt3(a));
return 0;
}
Result is for x=27: 0.0000?
Where is my mistake?
While the function returns an int, that value is printed with the wrong format specifier, %f instead of %d.
Change the signature (and the name, if I may) into something like this
double cube_root(double x) { ... }
Or change the format specifier, if you really want an int.
Following the explanation from tutorialspoint, which states, that the basic idea is to implement the Newton Raphson method for solving nonlinear equations, IMHO, the code below displays this fact more clearly. Since there is already an accepted answer, I add this answer just for future reference.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
double rootCube( double a)
{
double x = a;
double y = 1.0;
const double precision = 0.0000001;
while(fabs(x-y) > precision)
{
x = (x + y) / 2.0;
y = a / x / x;
}
return x;
}
int main(int argc, const char* argv[])
{
if(argc > 1)
{
double a =
strtod(argv[1],NULL);
printf("cubeRoot(%f) = %f\n", a, rootCube(a));
}
return 0;
}
Here, in contrast to the original code of the question, it is more obvious, that x and y are the bounds, which are being improved until a sufficiently accurate solution is found.
With modification of the line in the while block, where y is being updated, this code can also be used to solve similar equations. For finding the square root, for example, this line would look like this: y = a / x.

Trying to Approximate Euler's number in C

I am trying to approximate Euler's number using the formula (1+(1/n))^n.
The compiler is telling me that there is an "expected expression before 'double'"
Here is the code:
#include <stdio.h>
#include <math.h>
int main()
{
int x, y, power;
int num = 1;
int position = 1;
while (position <= 100)
{
num = 1/num;
num = num + 1;
x = num;
power = double pow(x, x); //here
printf("%f", power);
position += 1;
num = position;
}
}
If you want a number to be a double (number with decimals), you need to define it as a double, not an integer. I have this code which should solve your problem. Also make sure to compile gcc FILEPATH -lm -o OUTPUTPATH if you are using UNIX.
#include <stdio.h>
#include <math.h>
int main()
{
double x, y, power, num = 1; //doubles allow for decimal places so declare it as double
int position = 1; //Position seems to only be an integer, so declare it as an int.
while (position <= 100)
{
num = 1/num;
num++;
x = num;
power = pow(x, x);
printf("%f", power);
position += 1;
num = position;
}
}
Another option is a for loop:
#include <stdio.h>
#include <math.h>
int main()
{
double x, y, power, num = 1;
for (int i = 1; i <= 100; i++) {
num = 1/num;
num = num + 1;
x = num;
power = pow(x, x);
printf("%f", power);
position += 1;
num = i;
}
}
If you are trying to approximate Euler's number, I don't see why not just try something like:
static const double E = 2.718281828459045;
I have simply corrected syntax errors in your program, but I don't think it will actually get you E. See this page about calculating E in C.
I'm no C master but isnt just calling double by itself a type declaration and not type casting? wouldnt it be power = (double) pow(x, x); if you are type casting? see: https://www.tutorialspoint.com/cprogramming/c_type_casting.htm
I reworked some mistakes in your code and think it should work now; however, the style, which I kept untouched, is confusing.
#include <stdio.h>
#include <math.h>
int main()
{
double power; //stores floating point numbers!
double num = 1;//stores floating point numbers!
int position = 1;
while (position <= 100)
{
num = 1/num;
num = num + 1;
power = pow(num, position); //x not needed, this is what you ment
printf("%f\n", power); //%d outputs decimal numbers, f is for floats
position += 1;
num = position;
}
}
To improve your code, I would suggest to simplify it. Something along the lines of this
#include <stdio.h>
#include <math.h>
int main()
{
double approx;
for(int iter=1; iter<=100; iter++){
approx=pow((1+1./iter),iter);
printf("%f\n", approx);
}
}
is much easier to understand.

Calculate sin(x) and cos(x) using Taylor Series in C [duplicate]

I have been struggling with this code and just do not seem to grasp what I am doing wrong.
The code is suppose to calculate : Sum of a series of "Cosine" with pattern [(-1)^i(x)^2i]/(2i)!
Here is my code thus far:
#include <stdio.h>
#include <math.h>
float factorial(int n){
if (n==0)
return 1;
else
return 2*n*factorial(n-1);
}
int main (){
float i, n;
float sum=0;
printf("Enter desired interger: ");
scanf("%f", &n);
for (i=0; i<=1; i++)
sum = sum + (pow(-1,i)*pow(n,2*i))/(factorial(n));
printf("The value is %f\n", sum);
return 0;
}
I still working on it, any info or help will be much appreciated!
edit:
Just fixed it guys, this is new format I had to use for my professor:
#include <stdio.h>
#include <math.h>
int factorial(int n)
{
if (n==0) return 1;
else
return n*factorial(n-1);
}
float mycos(float x)
{
float sum=0;
int i;
for (i=0;i<=10;i++) sum = sum + (pow(-1,i)*pow(x,2*i))/factorial(2*i);
return sum;
}
int main()
{
int i=1;
printf(" x mycos(x) cos(x)\n");
for (i=1;i<=10;i++)
printf(" %f %f %f\n", i*.1, mycos(i*.1), cos(i*.1));
return 0;
}
Thank you all for your explanations, they helped out Immensely!
One thing I see, is that your for loop within main only runs through 2 real iterations, once for i == 0, and again for i == 1.
For the taylor expansion to work fairly effectively, it needs to be run through more sequence terms (more loop iterations).
another thing I see, is that your denominator is the n! rather than (2 * n)!
For efficiency, I might also implement the factorial routine as follows:
unsigned int factorial(int n){
unsigned int product = 1;
for(int I = 1; I <= n; I++) product *= I;
return product;
}
The above factorial routine is for a more EXACT factorial calculation, which perhaps you don't need for this purpose. For your purposes, perhaps the floating point variant might be good enough.
float factorial(int n){
float product = 1;
for(int I = 1; I <= n; I++) product *= (float)I;
return product;
}
I should also note why I am stating to perform factorial in this manner. In general a loop construct will be more efficient than its recursive counterpart. Your current implementation is recursive, and thus the implementation I provide SHOULD be quite a bit more efficient from both performance, and memory utilization.
Considering computation expense, you need to stop calculating the series at a point. The more you go, the more precise the result will be, but the more your program spends time. How about this simple program:
#include <stdio.h>
#include <math.h>
#define ITERATIONS 10 //control how far you go
float factorial(int n){
if (n==0)
return 1;
else
return n*factorial(n-1);
}
int main (){
float n;
float sum=0;
printf("Enter desired float: ");
scanf("%f", &n);
int c, i;
for (i=0; i<=ITERATIONS; i++) {
c = (i%2)==0? 1 : -1;
sum = sum + (c*pow(n,2*i+1))/(factorial(2*i+1));
}
printf("The value is %f\n", sum);
return 0;
}
1.) You are only multiplying even no.s in factorial function return 2*n*factorial(n-1); will give only even no.s. Instead you can replace n with 2n here- sum = sum + (pow(-1,i)*pow(n,2*i))/(factorial(2n)); This will give the correct (2n!).
2.) Check for the no, of iterations for (i=0; i<=1; i++) this will only run your loop twice. Try more no. of iterations for more accurate anwer.
Why are you calculating power etc for each item in the series? Also need to keep numbers in a suitable range for the data types
i.e. for cos
bool neg_sign = false;
float total = 1.0f;
float current = 1.0f;
for (int i = 0; i < length_of_series; ++i) {
neg_sign = !neg_sign;
current = current * (x / ((2 * i) + 1)) * (x / (( 2 * i) + 2));
total += neg_sign ? -current : current;
}
EDIT
Please see http://codepad.org/swDIh8P5
#include<stdio.h>
# define PRECISION 10 /*the number of terms to be processed*/
main()
{
float x,term=1,s=1.0;
int i,a=2;
scanf("%f",&x);
x=x*x;
for(i=1;i<PRECISION;i++)
{
term=-term*x/(a*(a-1));
s+=term;
a+=2;
}
printf("result=%f",s);
}
Your factorial() function actually calculates 2n.n!, which probably isn't what you had in mind. To calculate (2n)!, you need to remove the 2* from the function body and invoke factorial(2*n).

Recursive exponentiation

so I have to write a recursive algorithm for exponentiation and I have to use this to make the algorithm faster: and then I'd have to figure out how many time multiplication is happening. I wrote it, but I am not sure if I am right - also I need some help with figuring out the multiplication part.
#include <stdio.h>
#include <math.h>
double intpower(double x, int n)
{
double result;
if(n>1&&n%2!=0) {result=x*intpower(x,(n-1)/2)*intpower(x,(n-1)/2);}
if(n>1&&n%2==0) {result=intpower(x,n/2)*intpower(x,n/2);}
if(n==1) return x;
else return result;
}
int main()
{
int n;
double x,result;
printf("x\n");
scanf("%lf", &x);
printf("n\n");
scanf("%d", &n);
printf("result = %.2f\n", intpower(x,n));
return 0;
}
The inductive definitions are saying
If k is even, then x^k = [ x^(k/2) ] ^ 2
If k is odd, then x^k = x * [ x^(floor(k)/2) ] ^ 2
With these it's a bit easier to see how to arrange the recursion:
#include <stdio.h>
double int_pwr(double x, unsigned k)
{
if (k == 0) return 1;
if (k == 1) return x; // This line can be omitted.
double y = int_pwr(x, k/2);
return (k & 1) ? x * y * y : y * y;
}
int main(void)
{
double x;
unsigned k;
scanf("%lf%u", &x, &k);
printf("x^k=%lg\n", int_pwr(x, k));
return 0;
}
I've changed types to be a bit more logical and saved an exponential (in k) amount of work that the OP's solution does by making two recursive calls at each level.
As to the number of multiplications, it's pretty easy to see that if k's highest order bit is 2^p (i.e. at position p), then you'll need p multiplications for the repeated squarings. Another way of saying this is p = floor(log_2(k)). For example if k=4=2^2, you'll square the square to get the answer: 2 multiplications. Additionally you'll need q-1 more, where q is the number of 1's in k's binary rep. This is the number of times the check for "odd" will be true. I.e. if k = 5 (which has 2 bits that are 1's), you'll square the square and then multiply the result by x one more time. To summarize, the number of multiplications is p + q - 1 with p and q as defined above.
To figure out how many times multiplication is happening, you could count them in intpower().
static int count = 0;
double intpower(double x, int n) {
double result;
if(n>1&&n%2!=0) {result=x*intpower(x,(n-1)/2)*intpower(x,(n-1)/2); count += 2;}
if(n>1&&n%2==0) {result=intpower(x,n/2)*intpower(x,n/2); count++;}
if(n==1) return x;
else return result;
}
int main() {
int n;
double x,result;
printf("x\n");
scanf("%lf", &x);
printf("n\n");
scanf("%d", &n);
mcount = 0;
printf("result = %.2f\n", intpower(x,n));
printf("multiplcations = %d\n", mcount);
return 0;
}
Try this
double intpower(double x, int n)
{
if(n == 0) return 1;
if(n == 1) return x;
if(n%2!=0)
{
return x*intpower(x,(n-1));
}
else
{
x = intpower(x,n/2);
return x*x;
}
}
or you can reduce your function to one line
double intpower(double x, int n)
{
return n == 0 ? 1 : n%2 != 0 ? x*intpower( x, (n-1) ) : (x = intpower(x, n/2), x*x);
}

recursive segmentation fault

So I wrote a header that uses recursion to compute several mathematical functions. Including the cosine function and exponential function( e^x). Now the cosine functions works just fine but e^x produces a segmentation fault even though both use the same recursive procedure. So here is the code from the header file I created "c_math.h":
#define PI 3.141592
static unsigned int n;
................
uint32_t Factorial(unsigned int p)
{
if(p==0){
return(1);
}else if(p>0){
return p*Factorial(p-1);
}
};
double EXP(double x)
{
int N = n;
double F = (double)Factorial(n);
if(n==0){
return (1.0);
}else{
return EXP(x)+(Pow(x,N)/F);
}
}
double cosine(double x)
{
int N = (2*n);
double F = (double)(Factorial(2*n)*(-1^n));
if(n==0){
return(1.0);
}else if(n==1){
return 1+(Pow(x,2)/2);
}else if(n>1){
return cosine(x)+(Pow(x,N)/F);
}
};
double cos(double x){
bool halt = false;
double COS;
n = 0;
while(halt==false){
int N = (2*n);
double F = (double)(Factorial(2*n)*(-1^n));
COS = cosine(x);
if(abs(Pow(x,N)/F)<=0.0001){
halt = true;
}else{
n++;
}
}
return COS;
}
double e(double x){
bool halt = false;
double E;
n = 0;
while(halt==false){
int N = n;
double F = (double)(Factorial(n));
E = EXP(x);
if(abs(Pow(x,N)/F)<=0.0001){
halt = true;
}else{
n++;
}
}
return E;
}
The .c file with the main function:
include <stdio.h>
#include <cmath.h>
int main()
{
printf("\n");
printf("cos(2.2) = %4.6f\n",cos(2.2));
printf("\n");
printf("e(2.2) = %4.6f\n",e(2.2));
printf("\n");
}
After I compile it and then execute from the terminal prompt, the output looks like this:
zermacr0yd#DALEK /usr/lib/gcc/x86_64-linux-gnu/4.7.3/include $ ./mathtest
cos(2.2) = -0.588501
Segmentation fault
So as you can see the Cosine function works as it should but e^x produces a segmentation fault. Now the function e^x is strictly increasing for x > 0 and strictly decreasing for x < 0, but mathematically the power series should converge for all values of x which means that eventually when the series index n becomes high enough, the value of the nth term should fall below 0.0001. So what is going on here?
All your functions are using a variable n which I'm assuming is declared globally but only defined locally in e. You should provide a local definition of n for each function: int n = 0;.
Unix or the POSIX standard defines a tool named bc, which is a (very basic) multi-precision command line calculator. With it comes a numerical library that provides explicit implementations for exp, cos and sin and others. Study that for efficient, precise algorithms. The manpage, for instance at
http://www.gnu.org/software/bc/manual/html_mono/bc.html#SEC18
contains the implementation for exp(x) starting at the line define e(x).
Basically, for the Taylor series to work you first have to reduce the argument as close to zero as possible. bc mainly uses the technique of halving-and-squaring. For sin and cos the periodicity and symmetry can also be used.
The full bc library can be found at
http://code.metager.de/source/xref/gnu/bc/1.06/bc/libmath.b
double EXP(double x) {
/* other code that doesn't change x */
if(n==0) {
return 1.0;
} else {
return EXP(x) + /* other code */;
}
}
Let's say we want to calculate EXP(2).
EXP starts running, gets to the second return statement, and calls EXP(2) again.
Which calls EXP(2) again.
Which calls EXP(2) again.
Which calls EXP(2) again. Etc.
Recursion only works if the function eventually stops recursing.
A no-nonsense implementation of the cosine Taylor series is
#include<stdio.h>
#include<math.h>
double cos_taylor(double x) {
double mxx=-x*x, a=1, c=0;
unsigned int k=1;
while(1+a!=1) {
c+=a;
a*=mxx/(k++)/(k++);
}
return c;
}
int main() {
double x;
for(x=-0.5; x<3.2; x+=0.1)
printf(" x=%10.7f \t math.cos(x)=%20.16g \t taylor.cos(x)=%20.16g\n",
x, cos(x), cos_taylor(x));
return 0;
}

Resources