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.
Related
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;
}
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.
Thanks a lot people for your help so far but I made a big mistake I need the derivation of a function at a specific point!
I have to calculate the first derivation of a function and I really have no clue how to get there. If I just had to calculate it for a function with just a X^1 I would know how to but I'm really stuck here.
Old Stuff:
A function can look like 2*x^2+1.
The method has to look like this: double ab(double (f)(double),double x)
and my professor gave us the hint that we might should use the function:
(f(x0+∆x)−f(x0))/((x0+∆x)−x0).
Sorry for my bad English and thanks for any kind of hint or tip in advance.
this sample will get you started :
#include<stdio.h>
#include <stdlib.h>
float func(float x)
{
return(2*x*x + 1);
}
int main(){
float h=0.01;
float x;
float deriv, second;
printf("Enter x value: ");
scanf("%f", &x);
// derivative at x is the slope of infinitely small
// line of the function
deriv = (func(x+h) - func(x))/h; // I assumed the length to be h
//for second derivative you can use:
second = (func(x+h) - 2*func(x) + func(x-h))/(h*h);
printf("%f\n", deriv);
return 0;
}
The idea is approximate the first derivative of f() at x with the slope of the secant line through the points (x, f(x)) and (x+∆x, f(x+∆x)).
The Wikipedia article should get you started.
Hi I am new to C programming, I am just trying to replace part of my code with a function call but I don't know how to do it properly, please help.
I just want the line d = ... to be equivalent to the line e = ...
#include <stdio.h>
#include <math.h>
double dist(int i, int j, double v[100][2])
{
return sqrt( pow((v[j][0] - v[i][0]),2) + pow((v[j][1] - v[i][1]), 2) )
}
main()
{
double v[100][2], d, e;
v[1][0] = 0;
v[1][1] = 1;
v[2][0] = 1;
v[2][1] = 1;
d = sqrt( pow((v[1][0] - v[2][0]),2) + pow((v[1][1] - v[2][1]), 2) );
e = dist(1,2,v);
printf("\n%f\n",d);
printf("\n%f\n",e);
}
double dist(int i, int j, double (*v)[2])
{
return sqrt( pow((v[j][0] - v[i][0]),2) + pow((v[j][1] - v[i][1]), 2) );
}
d = dist(0,1,v)
Or dist(1,0,v)
Distance between point 0 and point 1 ... Order does not matter.
EDIT: What I have above is a function CALL, as requested. d= is equivalent to e= ... to write another function is quite the waste of code and more importantly, not a realization of what a function is used for. I stick by my answer.
If you wanted the same thing for different types, you can use a macro (not recommended for this case since a decent compiler will inline the function call to Cato's function) but just for educational purposes
#define dist(i,j,v) sqrt(pow((v[j][0]-v[i][0]),2)+pow((v[j][1]-v[i][1]),2))
Just keep in mind that sqrt returns a double, so if you want float or long double returns, you'll need sqrtf or sqrtl.
The advantage to using macros for mathematical "functions" is that they get expanded out into the code prior to compile such that constants can be evaluated into the computation and can sometimes reduce the entire calculation down to a much simpler computation or sometimes even a constant value.
Mike is correct on the mathematical properties, though precision may cause the 2 values to differ slightly (usually this difference is unwanted).
I have a code, that was not made by me.
In this complex code, many rules are being applied to calculate a quantity, d(x). in the code is being used a pointer to calculate it.
I want to calculate an integral over this, like:
W= Int_0 ^L d(x) dx ?
I am doing this:
#define DX 0.003
void WORK(double *d, double *W)
{
double INTE5=0.0;
int N_X_POINTS=333;
double h=((d[N_X_POINTS]-d[0])/N_X_POINTS);
W[0]=W[0]+((h/2)*(d[1]+2.0*d[0]+d[N_X_POINTS-1])); /*BC*/
for (i=1;i<N_X_POINTS-1;i++)
{
W[i]=W[i]+((h/2)*(d[0]+2*d[i]+d[N_X_POINTS]))*DX;
INTE5+=W[i];
}
W[N_X_POINTS-1]=W[N_X_POINTS-1]+((h/2)*(d[0]+2.0*d[N_X_POINTS-1]+d[N_X_POINTS-2])); /*BC*/
}
And I am getting "Segmentation fault". I was wondering to know if, I am doing right in calculate W as a pointer, or should declare it as a simple double? I guess the Segmentation fault is coming for this.
Other point, am I using correctly the trapezoidal rule?
Any help/tip, will very much appreciate.
Luiz
I don't know where that code come from, but it is a lot ugly and has some limits hard-encoded (333 points and increment by 0.003). To use it you need to "sample" properly your function and generate pairs (x, f(x))...
A possible clearer solution to your problem is here.
Let us consider you function and let us suppose it works (I believe it does't, it's a really obscure code...; e.g. when you integrate a function, you expect a number as result; where's this number? Maybe INTE5? It is not given back... and if it is so, why the final update of the W array? It's useless, or maybe we have something meaningful into W?). How does would you use it?
The prototype
void WORK(double *d, double *W);
means the WORK wants two pointers. What these pointers must be depends on the code; a look at it suggests that indeed you need two arrays, with N_X_POINTS elements each. The code reads from and writes into array W, and reads only from d. The N_X_POINTS int is 333, so you need to pass to the function arrays of at least 333 doubles:
double d[333];
double W[333];
Then you have to fill them properly. I thought you need to fill them with (x, f(x)), sampling the function with a proper step. But of course this makes no too much sense. Already said that the code is obscure (now I don't want to try to reverse engineering the intention of the coder...).
Anyway, if you call it with WORK(d, W), you won't get seg fault, since the arrays are big enough. The result will be wrong, but this is harder to track (again, sorry, no "reverse engineering" for it).
Final note (from comments too): if you have double a[N], then a has type double *.
A segmentation fault error often happens in C when you try to access some part of memory that you shouldn't be accessing. I suspect that the expression d[N_X_POINTS] is the culprit (because arrays in C are zero-indexed), but without seeing the definition of d I can't be sure.
Try putting informative printf debugging statements before/after each line of code in your function so you can narrow down the possible sources of the problem.
Here's a simple program that integrates $f(x) = x^2$ over the range [0..10]. It should send you in the right direction.
#include <stdio.h>
#include <stdlib.h>
double int_trapezium(double f[], double dX, int n)
{
int i;
double sum;
sum = (f[0] + f[n-1])/2.0;
for (i = 1; i < n-1; i++)
sum += f[i];
return dX*sum;
}
#define N 1000
int main()
{
int i;
double x;
double from = 0.0;
double to = 10.0;
double dX = (to-from)/(N-1);
double *f = malloc(N*sizeof(*f));
for (i=0; i<N; i++)
{
x = from + i*dX*(to-from);
f[i] = x*x;
}
printf("%f\n", int_trapezium(f, dX, N));
free(f);
return 0;
}