Arctan Taylor Series in C - c

I need to perform the Taylor Series for arctangent 50 times. Meaning 50 numbers between the domain of the arctan Taylor Series which is [-1,1]. I've tested it out with manual user input and it works fine, but the for loop for the 50 different inputs which I increment in the code by 0.01 and their corresponding results has been unsuccessful. I've tried everything I could think of so far, I'm out of ideas. Any help would be appreciated. Is there an issue with my brackets surrounding the Taylor Series that's conflicting with the other for loop? I've suspected it was the brackets but nothings worked when I attempted to fix it.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
main (void) {
double n;
double x;
double tSeries=0.0;
double t2;
double t1;
for(n=0;n<=50;++n) {
for(x=-1;x<=1;x=x+0.01) {
t1=(pow(x,2*n+1))*pow(-1,n);
t2=t1/(2*n+1);
tSeries+=t2;
printf("arctan(%lf)=%lf\n",x,tSeries);
}
}
return 0;
}

In the code you've posted the inner loop is over the variable x, and the outer loop is over the power n.
I think you want to sum over values of n for each value of x, so the loop over n should be the inner loop.
I think you also need to zero your sum, tSeries for each value of x.
Finally, I expect you want to print the answer after calculating the sum, so printf should be outside the n loop.
There are a few tricks to the evaluation of power series. I like Numerical Recipes for this sort of thing. Try chapter 5 on the evaluation of functions. (Numerical Recipes in C, Press et al., 2nd Ed., 1992, CUP.)
One thing to note right away is that with the upper limit of the power series fixed, you are evaluating a polynomial. Section 5.3 of my copy of NR recommends strongly against using a sum of calls to pow(). They are quite firm about it!
Let me know if you want me to post correct code.

You got the loops mixed, the inner one goes out and vice versa.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(void)
{
double n;
double x;
double tSeries = 0.0;
double t2;
double t1;
for (x = -1; x <= 1; x += 0.01) {
for (n = 0; n <= 50; n++) {
t1 = (pow(x, 2 * n + 1)) * pow(-1, n);
t2 = t1 / (2 * n + 1);
tSeries += t2;
}
printf("arctan(%lf)=%lf (%lf)\n", x, tSeries, atan(x));
tSeries = 0.0;
}
return 0;
}

Related

Calculate cosine in C

We are doing C Programming in school and we have to calculate the cosine of a number with use of the "Taylor series" (https://en.wikipedia.org/wiki/Taylor_series). I know C programming but that what we have to do has not really much to do with programming itself more than being good in math.
If you put in your calculator cos(50) it's 0.6427.... That's what we have to do in C. There is the cos() function in math.h but that's not actually the cosine. I am overwhelmed with this and don't really know what we have to do. It should look something like this:
#include <stdio.h>
#include <conio.h>
#include <math.h>
int fac(int n);
double meincosinus(double x);
void main() {
double x;
double y;
int i;
printf("geben sie eine zahl ein\n");
scanf_s("%lf", &x);
y = meincosinus(x);
printf_s("cos(%lf)=%lf\n", x, y);
y = sin(x);
printf_s("cos(%lf)=%lf\n", x, y);
scanf_s("%d", &i);
printf_s("%d\n", i);
_getch();
}
int fac(int n) {
int prod = 1;
int i;
for (i = 1; i <= n; i++)
{
prod *= i;
}
return prod;
}
double meincosinus(double x)
{
double erg = 0;
int n;
for (n = 0; n <= x; n++)
{
x = fac(n);
erg += pow(-1, n) * pow(x, (2 * n)) / fac(2 * n);
}
return erg;
}
This code runs but the output is wrong.
Not an answer (but, well, I am a teacher myself, I am not gonna make your homework :)). But a few questions you should ask yourself and that might help you
Why are you comparing your Taylor computation of cosinus with the "real" sinus? Shouldn't y=sin(x) be y=cos(x), for a pertinent comparison?
why are you doing this: x = fac(n);? You are overwriting your x argument to "meinconsinus". You can't expect meincosinus(50) to really compute cos(50) if the first thing you do is overwriting that "50" with something else (namely n!).
also, why this for (n = 0; n <= x; n++). You know the Taylor formula better that I do (since you are studying it right now). It sure not supposed to stop after x iterations. x is rarely even an integer. It is supposed to be very small anyway. And could even be negative. So, question you've to ask yourself is, how many iterations (up to which term of the series) you want to compute. It is a rather arbitrary choice, since from Taylor point of view, answer is ∞. But on a computer, after a while it is no use to add extremely small numbers
Since I am mentioning the fact that x is supposed to be small: you can't compute cos(50) that way with a Taylor formula. You could compute cos(0.1) or even cos(1) maybe, with enough iterations. But 50 is not a small enough number. Plus, 50ⁿ will be very quickly out of control in your loop. If you really want meincosinus to be able to handle any number, you have first to reduce x, using trigonometric rules: cos(x)=cos(x)-2π; cos(x)=-cos(x); cos(x)=sin(π/2-x); ... There are some better rules, but with those simple ones, you can have x in [0,π/4]. Since π/4<1, at least you don't have an explosive xⁿ.
Also, but that is an optimization, you don't really need to compute neither (-1)ⁿ with pow (just alternate a int sign variable, between -1 and 1 at each iteration), nor x²ⁿ (just multiply a double x2n=1 by x*x each iteration), nor fac(2n) (just multiply a f=1 variable by (n-1)×n, being careful with 0 case, at each iteration.

Approximating the value of pi in C using Viete's Formula

My assignment this week in my CS class is create a program to approximate for pi using Viète's Formula. I've been trying to start for the past hour or so, but I'm honestly not even sure how to begin. All the work I have gotten done doesn't work.
I'm assuming my professor wants us to use the "while" loop, as we've been using it a lot in class lately. We've also been using "if" statements a lot, although I'm not sure if we need to use those here.
Can anyone help me find a starting off point or explain how I could go about doing this?
//here is some of the work i have attempted that doesn't work because i don't know what to do
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main()
{
double n,pi,f,i;
printf("enter the number of iterations to approximate for pi\n");
scanf("%lf\n", &n);
pi = 2 / f;
i = 1;
f = sqrt(2);
while (i<=n)
{
}
To start with the code you posted:
1) You don't want i and n to be of type double Change them to int
2) You should always check the value returned by scanf Like: if (scanf(%d) != 1) {// add error handling here ...}
3) pi = 2 / f; is undefined behavior as f is uninitialized
Then your assignment:
I'll not give you a complete solution but instead give you a hint so you can continue your work.
The formula needed can be found here: https://en.wikipedia.org/wiki/Viète%27s_formula#Interpretation_and_convergence
Your first task is to calculate a[n] given that
a[1] = sqrt(2)
a[n] = sqrt(2 + a[n-1])
You can do that using a while-loop (though I would prefer a for-loop). It could be like:
#include <stdio.h>
#include <math.h>
int main()
{
int n, i;
n = 5;
i = 1;
double an = sqrt(2);
while(i <= n)
{
printf("a%d = %.10f\n", i, an);
an = sqrt(2 + an);
++i;
}
return 0;
}
This gives you:
a1 = 1.4142135624
a2 = 1.9615705608
a3 = 1.9975909124
a4 = 1.9998494037
a5 = 1.9999905876
So now that you know how to calculate a1, a2, a3, ... you just need to put it together using:
(image from: https://en.wikipedia.org/wiki/Viète%27s_formula#Interpretation_and_convergence)
and find pi.

Equation having sqrt ,abs and the derivative on c

First, i would like to tell you that english isnt my nature language so maybe a word or meaning i am not express it right.The problem now is i recently did one exercise and the question was to use the Newton-Raphson method for sqrt.Anyway, i think this(sqrt) i have done it i am not sure about it.I couldnt do the derivative.Also,i think i have some mistakes on my code if you could fix it i would be greatful.The equation is
x=sqrt(num)=>x*x=num=>f(x,num)=x*x-num=0
#include<stdio.h>
#include<stdlib.h>
#include <math.h> /* i use it for pow */
#definde f(x) ((x*x-num)/2x) /* this is the equation */
main(){
double num=8; /* i put what ever i want so i put 8 */
double result;
double oldx=2; /* i put what ever i want so i chose to put 2 */
double x;
x=num/2;
result=sqrt(x);
printf("num= %d x= %16.lf\n",num,result);
while(abs(x-oldx)>pow(10,-15)){ /* |x-oldx|> pow(10,-15).I am not sure about abs here */
x=oldx; /* i give to x the price of oldx */
printf("x=%lf",x); /* its double so i use lf */
x=(pow(x,2)-num)/2*x; /* #definde f(x) ((x*x-num)/2x) this is it but i wrote it in that way.Maybe i dont know it could be false */
printf("x=%lf",x);
}
printf("x= %lf result= % 16.lf ");
system("pause");
}
There are numerous mistakes in your code:
abs should be fabs.
The while loop keeps setting x=oldx for each iteration and oldx never changes, so the loop never makes any progress. It should really set oldx=x.
/2*x does not divide by 2*x as you require, because * and / have the same operator precedence. You need to replace it with /(2*x) or /2/x.
At each step, you are calculating xₙ₊₁ = f(xₙ) / fʹ(xₙ), but the correct formula is xₙ₊₁ = xₙ − f(xₙ) / fʹ(xₙ).
In addition, there is no need to use the pow function to calculate 10⁻¹⁵ or x² when a literal constant or a simple multiplication will do.
Here is a complete solution:
#include <stdio.h>
#include <math.h>
int main(void) {
double num = 8; /* i put what ever i want so i put 8 */
double result;
double x;
double oldx;
double residual;
unsigned int iterations=0;
result = sqrt(num);
x = num / 2; /* initial guess */
printf("sqrt(%g)=%.16g\n", num, result);
do {
printf("x%u=%.16g\n", iterations, x);
iterations++;
oldx = x;
x = x - ((x * x - num) / (2 * x));
residual = x - oldx;
} while (fabs(residual) > 1e-15);
printf("x%u=%.16g residual=%.16g\n", iterations, x, residual);
return 0;
}

How would I go about converting these equations to C code?

I have these two equations
and I need to convert them to C code where you inputk and x. The thing is I don't get that advanced levels of math, neither did I learn C in the past :D
Can anyone show me step by step what built-in functions can be used for this and how exactly should the logic behind the app work?
Cheers!
Your formula is wrong. As shown here (along with the proof of the derivation) the correct formula is
You have k and n swapped in your summation. The inputs should then be x and n. The correct code is then:
#include <math.h>
double sum_of_sin(double x, int n) {
if (sin(x/2) == 0.0) {
return 0.0; //prevent division by 0 for x multiple of 2π
}
return sin(n*x/2) * sin((n+1)*x/2) / sin(x/2);
}
You can include the file math.h which has inbuilt functions like cos() and sin().
For instance:
#include <stdio.h>
#include <math.h>
int main ()
{
double res;
ret = cos(45);
printf("The cos of angle 45 is %f",res);
return 0;
}
Hope it helps..
You have an equation that consists of two formulae. It is easy to write the two parts out, but it can be hard to find a solution. The right-hand part of the first formula would be:
float RHvalue;
RHvalue = (sin( ((n+1.0)*x) / 2.0 ) * sin(n * x/2.0) ) / sin(x/2.0);
now, what the values of kx would be, is another matter, though it would be easy to sum them.

Number of iterations to get desired accuracy in C (ln x, taylor polynomial)

I am trying to write a c program to
get result of "n" iterations of taylor series for ln(x)
get number of iterations needed to get the result with desired accuracy compared to log(x) from
So far i have created two functions for taylor series, first one for 0 < x < 1 and second for x > 1. To make it simple, I will post just the second one because these functions work fine. The input is "x" as the parameter of ln() and "n" as the number of iterations. As I can't use math.h I had to create "xTOn" function which simply does the x^n. In this function I have implemented following formula:
Taylor series
double taylorTheSecond(double x, int n) // second formula for taylor x > 1
{
double sum = 0.0;
for (int i = 1; i <= n; i++)
{
sum += xTOn((x-1)/x, i) / i;
}
return sum;
}
I have also the function to count number of needed iterations but it compares the result with the function log() from math.h, which is undiserable. It should be done by comparing two consecutive iterations but i have no idea how to do that because i don't understand what's the point when you compare two inaccurate numbers. Now, "x" is the parameter of ln function and "eps" is desired accuracy (e.g. 0.001 or 1e-3 ...).
#include <math.h>
int iterations(double x, double eps)
{
int i = 1;
while(1)
{
if (fabs(taylorTheSecond(x, i) - log(x)) <= eps)
{
break;
}
i++;
}
return i;
}
This is really simple. But to count the iterations without using the math library, it just looks impossible to me. I will be grateful for any suggestions how to get this done :).
You could try to exit the loop when the fluctuation in the results of successive iterations falls below your desired resolution. i.e. fabs(taylorTheSecond(x, i) - taylorTheSecond(x, i - 1)) < 1e-3 or whatever.
.. and obviously use a variable to store the previous value; also instead of re-calculating the Taylor series each time, just calculate the next term, and see if this falls below the desired resolution.

Resources