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;
}
Related
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.
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.
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;
}
Check the image
This is my 1st post so have that in mind while reading my question.
I have an exam of a colloquium but my code does not provide me the correct result.
So if anyone could help me that would be great. :)
These are the informations that are provided in the exam:
A function y=f(x)=ax^2+bx+c
We have to find the surface that is below the chart but keep in mind that dx(Delta X)=B-A and the height goes like this: A,A+dx,A+2dx, .... , B-dx.
As dx value gets lower the surface will be more accurate.
You have to write the program so that the surface with precision 0.001
This is my code so could someone who is good in C check it please.
Thank you.
#include <stdio.h>
#include <math.h>
int main()
{
int a,b,c;
double A,B,dx,p,D,q,x,y,nv,nv1,nv2,sv;
do{
printf("Insert a & b: "),scanf("%lf %lf",&A,&B);
} while(A<1 || B<1);
nv=dx=B-A;
do{
printf("enter odds: "),scanf("%d %d %d",&a,&b,&c);
p=(-b)/2;
D=sqrt(pow(b,2)-4*a*c);
q= -D/4*a;
} while( a<0 || p<0 || q<0);
do{
sv=nv;
dx/=2;
nv=0;
for(x=A;x<p;x+=dx)
for(dx=B-A;dx<q;dx/=2)
nv1+=x*dx;
for(y=p;y<=B;y+=dx)
for(dx=q;dx<B;dx/=2)
nv2+=y*dx;
nv=nv1+nv2;
}while(fabs(nv-sv)>0.001);
printf("The surface is %lf",nv);
return 0;
}
You want to find the approximation of a definite integral of a quadratic function. There are several issues with your code:
What is the restriction of A ≥ 1 and B ≥ 1 for? A parabola is defined over the whole abscissa. If anything, you should enforce that the input is numeric and that two values were given.
You don't need to find the vertex of the parabola. Your task is to create small rectangles based on the left x value of each interval as the image shows. Therefore, you don't need p and q. And you shouldn't enforce that the vertex is in the first quadrant on the input without indication.
Why are the coefficients of the parabola integers? Make them doubles to be consistent.
Because you don't need to know the vertex, you don't need to split your loop in two. In your code, you don't even check that p is between A and B, which is a requirement of cour code.
What is the inner loop for? You are supposed to just calculate the area of the current rectangle here. What's worse: you re-use the variable dx as iteration variable, which means you lose it as an indicator of how large your current interval is.
The repeated incrementing of dx may lead to an accumulated floating-point error when the number of intervals is large. A common technique to avoid this is to use an integer variable for loop control and the determine the actual floating-point variable by multiplication.
The absolute value as a convergence criterion may lead to problems with small and big numbers. The iteration ends too early for small values and it may never reach the criterion for big numbers, where a difference of 0.001 cannot be resolved.
Here's a version of your code that puts all that into practice:
#include <stdio.h>
#include <math.h>
int main()
{
double a, b, c;
double A, B;
printf("Lower and upper limit A, B: ");
scanf("%lf %lf", &A, &B);
printf("enter coefficients a, b, c: ");
scanf("%lf %lf %lf", &a, &b, &c);
double nv = 0;
double sv;
int n = 1;
do {
int i;
double dx;
sv = nv;
n *= 2;
dx = (B - A) / n;
nv = 0;
for (i = 0; i < n; i++) {
double x = A + i * (B - A) / n;
double y = a*x*x + b*x + c;
nv += dx * y;
}
} while(fabs(nv - sv) > 0.0005 * fabs(nv + sv));
printf("Surface: %lf\n", nv);
return 0;
}
The code is well-behaved for empty intervals (where A = B) or reversed intervals (where A > B). The inpt is still quick and dirty. It should really heck that the entered values are valid numbers. There's no need to restrict the input arbitrarily, though.
I have a problem with a series of functions. I have an array of 'return values' (i compute them through matrices) from a single function sys which depends on a integer variable, lets say, j, and I want to return them according to this j , i mean, if i want the equation number j, for example, i just write sys(j)
For this, i used a for loop but i don't know if it's well defined, because when i run my code, i don't get the right values.
Is there a better way to have an array of functions and call them in a easy way? That would make easier to work with a function in a Runge Kutta method to solve a diff equation.
I let this part of the code here: (c is just the j integer i used to explain before)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int N=3;
double s=10.;
//float r=28.;
double b=8.0/3.0;
/ * Define functions * /
double sys(int c,double r,double y[])
{
int l,m,n,p=0;
double tmp;
double t[3][3]={0};
double j[3][3]={{-s,s,0},{r-y[2],-1,-y[0]},{y[1],y[0],-b}}; //Jacobiano
double id[3][3] = { {y[3],y[6],y[9]} , {y[4],y[7],y[10]} , {y[5],y[8],y[11]} };
double flat[N*(N+1)];
// Multiplication of matrices J * Y
for(l=0;l<N;l++)
{
for(m=0;m<N;m++)
{
for(n=0;n<N;n++)
{
t[l][m] += j[l][n] * id[n][m];
}
}
}
// Transpose the matrix (J * Y) -> () t
for(l=0;l<N;l++)
{
for(m=l+1;m<N;m++)
{
tmp = t[l][m];
t[l][m] = t[m][l];
t[m][l] = tmp;
}
}
// We flatten the array to be left in one array
for(l=0;l<N;l++)
{
for(m=0;m<N;m++)
{
flat[p+N] = t[l][m];
}
}
flat[0] = s*(y[1]-y[0]);
flat[1] = y[0]*(r-y[2])-y[1];
flat[2] = y[0]*y[1]-b*y[2];
for(l=0;l<(N*(N+1));l++)
{
if(c==l)
{
return flat[c];
}
}
}
EDIT ----------------------------------------------------------------
Ok, this is the part of the code where i use the function
int main(){
output = fopen("lyapcoef.dat","w");
int j,k;
int N2 = N*N;
int NN = N*(N+1);
double r;
double rmax = 29;
double t = 0;
double dt = 0.05;
double tf = 50;
double z[NN]; // Temporary matrix for RK4
double k1[N2],k2[N2],k3[N2],k4[N2];
double y[NN]; // Matrix for all variables
/* Initial conditions */
double u[N];
double phi[N][N];
double phiu[N];
double norm;
double lyap;
//Here we integrate the system using Runge-Kutta of fourth order
for(r=28;r<rmax;r++){
y[0]=19;
y[1]=20;
y[2]=50;
for(j=N;j<NN;j++) y[j]=0;
for(j=N;j<NN;j=j+3) y[j]=1; // Identity matrix for y from 3 to 11
while(t<tf){
/* RK4 step 1 */
for(j=0;j<NN;j++){
k1[j] = sys(j,r,y)*dt;
z[j] = y[j] + k1[j]*0.5;
}
/* RK4 step 2 */
for(j=0;j<NN;j++){
k2[j] = sys(j,r,z)*dt;
z[j] = y[j] + k2[j]*0.5;
}
/* RK4 step 3 */
for(j=0;j<NN;j++){
k3[j] = sys(j,r,z)*dt;
z[j] = y[j] + k3[j];
}
/* RK4 step 4 */
for(j=0;j<NN;j++){
k4[j] = sys(j,r,z)*dt;
}
/* Updating y matrix with new values */
for(j=0;j<NN;j++){
y[j] += (k1[j]/6.0 + k2[j]/3.0 + k3[j]/3.0 + k4[j]/6.0);
}
printf("%lf %lf %lf \n",y[0],y[1],y[2]);
t += dt;
}
Since you're actually computing all these values at the same time, what you really want is for the function to return them all together. The easiest way to do this is to pass in a pointer to an array, into which the function will write the values. Or perhaps two arrays; it looks to me as if the output of your function is (conceptually) a 3x3 matrix together with a length-3 vector.
So the declaration of sys would look something like this:
void sys(double v[3], double JYt[3][3], double r, const double y[12]);
where v would end up containing the first three elements of your flat and JYt would contain the rest. (More informative names are probably possible.)
Incidentally, the for loop at the end of your code is exactly equivalent to just saying return flat[c]; except that if c happens not to be >=0 and <N*(N+1) then control will just fall off the end of your function, which in practice means that it will return some random number that almost certainly isn't what you want.
Your function sys() does an O(N3) calculation to multiply two matrices, then does a couple of O(N2) operations, and finally selects a single number to return. Then it is called the next time and goes through most of the same processing. It feels a tad wasteful unless (even if?) the matrices are really small.
The final loop in the function is a little odd, too:
for(l=0;l<(N*(N+1));l++)
{
if(c==l)
{
return flat[c];
}
}
Isn't that more simply written as:
return flat[c];
Or, perhaps:
if (c < N * (N+1))
return flat[c];
else
...do something on disastrous error other than fall off the end of the
...function without returning a value as the code currently does...
I don't see where you are selecting an algorithm by the value of j. If that's what you're trying to describe, in C you can have an array of pointers to functions; you could use a numerical index to choose a function from the array, but you can also pass a pointer-to-a-function to another function that will call it.
That said: Judging from your code, you should keep it simple. If you want to use a number to control which code gets executed, just use an if or switch statement.
switch (c) {
case 0:
/* Algorithm 0 */
break;
case 1:
/* Algorithm 1 */
etc.