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

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.

Related

Why it asks the same but in the code theres only 1 printf()?

Im sorry but im just learning c, probably its easy to fix but i dont know how
In the code i just have 1 printf but in the terminal shows the same question 2 times. But finally the result is correct.
#include <stdio.h>
#include <math.h>
double lfDemanaTaxa(){
double i;
double d;
printf("Quant es la taxa interes nominal?\n");
scanf("%lf",&i);
d = i/100;
return d;
}
double lfDemanaMensualitat(){
double n;
scanf("%lf",&n);
return n;
}
int main(){
double a,b,c,TAE;
a = (1+lfDemanaTaxa()/lfDemanaMensualitat());
b = pow(a,lfDemanaMensualitat());
c = b -1;
TAE = c * 100;
printf("El TAE total es %.2lf%% \n", TAE);
return 0;
}
You call the lfDemanaMensualitat() function twice, and it does one call to printf(), so of course you're going to have two print-outs.
If you wanted to only call it once and store the value, you can something like this:
const double t = lfDemanaMensualitat();
const double a = (1 + lfDemanaTaxa()) / t;
const double b = pow(a, t);
And then compute c and TAE like you already do. This just saves the result of lfDemanaMensualitat() in a temporary variable called t.
By the way you should know that scanf() can fail, if the user enters things that don't match the specified conversion. You must check the return value to make sure it succeeded before relying on the input.

Arctan Taylor Series in 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;
}

Use of Ceil and Integers

So I just got my grade back from a school project that I did well on, but the grader took five points off because I didn't make a call to ceil(...). Its a parallel computing course using CUDA, but the question isn't directly related to any CUDA feature.
Here is the "offending" line:
dim3 dimGrid(n / dimBlock.x, n / dimBlock.y);
His claim is that I should have done:
dim3 dimGrid(ceil(n / dimBlock.x), ceil(n / dimBlock.y));
So my question is, why would I be marked off for this if n and dimBlock.* are integers? Their result will be calculated before ceil is even called and truncated. Thus it seems silly to mark off for that.
The following examples below seem to show that GCC optimizes the call out anyway when using -O2.
With ceil:
#include <stdio.h>
#include <math.h>
int main()
{
int m = 3, n = 5, o;
o = ceil(n / m);
printf("%d\n", o);
return 0;
}
Without:
#include <stdio.h>
#include <math.h>
int main()
{
int m = 3, n = 5, o;
o = n / m;
printf("%d\n", o);
return 0;
}
While I understand its only five points, I still want to understand why if I am completely wrong.
The grader probably meant that you needed to use the ceiling of the fraction n/d, and this is perfectly right: this way there will be enough blocks to cover n, the last block possibly being incomplete.
That does not mean that the appropriate implementation is with the C expression ceil(n/d). Indeed, the C / is an integer division and will discard the decimal part, actually taking the floor of the fraction.
You can use ceil((double)n/(double)d) instead.
But my favorite way would be without converting to doubles: (n+d-1)/d.
here, m = 3, n = 5
so, n / m= 1.67(approx);
since you are assigning it o which is of int type, it will truncate it. i.e, only stores the integer part not decimal part, so we have o=1. While if you will use ceil(n/m), output would be 2, which is then assigned to o. i.e, o=2.

Input a value for a scanf(), but nothing happens

I'm writing some code as part of a few assignment exercises to learn C programming from absolute basics, and I've run into a problem, which is probably quite simple to solve, but I'm completely stuck! I'm writing a program to implement a basic Newton's method for differentiation. Whenever I input an initial value to the scanf(), the program simply stops, doesn't return anything, terminate or freeze. Any help would be great.
Here is my code to start with:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//function to be used f(x) = cos(x)-x^3
//f'(x) = -sin(x)-3x^2
int main()
{
double x, xold;
printf("Enter an initial value between 0 and 1\n");
scanf("%lf",&xold);
double eps = 1e-12;
x = xold - ((cos(xold)-pow(xold,3))/(-(sin(xold)-(3*pow(xold,2)))));
while (fabs(x-xold)>eps)
{
x = xold - ((cos(xold)-pow(xold,3))/(-sin(xold)-(3*pow(xold,2))));
}
printf("The answer is %.12lf",x);
return 0;
};
In your while loop:
x = xold - ((cos(xold)-pow(xold,3))/(-sin(xold)-(3*pow(xold,2))));
the value of the = right operand is always the same, how could you exit the loop once you enter it?
Actually the thing is you are not updating your xold variable. Try the below modified code for your problem, see if I have done correctly:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
double x, xold;
printf("Enter an initial value between 0 and 1\n");
scanf("%lf",&x);
double eps = 1e-12;
x = x - ((cos(x)-pow(x,3))/(-(sin(x)-(3*pow(x,2)))));
while (fabs(x - xold)>eps)
{
xold = x;
x = x - ((cos(x)-pow(x,3))/(-sin(x)-(3*pow(x,2))));
}
printf("The answer is %.12lf\n",x);
return 0;
}

ProjectEuler2-(my own solution)

I have tried to solve Project Euler problem 2 by a for loop. I'm new to c programming and I cannot seem to get the algorithm right.
3524579
The for loop is suppose to look at for the 32 fibonacci which is less than 4000000. Then I have defined the fibonacci function and after than I want to add the even fibonacci numbers by the second for loop.
I get 3524579, can anyone help me with what I'm doing wrong?
/* Edited:
Ok, I rewrote the code using your tips. I do not understand why this does not work. I tried to write each steps down on paper:
The predicate is evaluated b mod 2 == 0, so the following happends:
sum = 2 + 0
a = b -> a == 2
b = sum -> b == 2
These steps iterate until the value 4mill. Can someone see what I fail to not see :p?*/
New edited version: I finally it work using a for-loop. Just wondering if there was a prettier way to do it using for-loop maybe.
#include <stdio.h>
int main() {
int a = 0;
int b = 1;
int result = 0;
int sum = 0;
for(;;){
if(!(b < 4000000)) break;
if(b % 2 == 0)
result = result + b;
sum = a + b;
a = b;
b = sum;
printf("%d\n", result);
}
}
A couple things:
Notice that your answer is equal to the 31st fib number + 1. This means you are replacing your total with new values on every iteration instead of keeping a running total.
Consider looping until the current fib number gets > 4M instead of figuring out beforehand that there are 32 fib numbers you need to look at.

Resources