How to write this function C - c

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).

Related

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.

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.

Modulo 2*Pi using SSE/SSE2

I'm still pretty new to using SSE and am trying to implement a modulo of 2*Pi for double-precision inputs of the order 1e8 (the result of which will be fed into some vectorised trig calculations).
My current attempt at the code is based around the idea that mod(x, 2*Pi) = x - floor(x/(2*Pi))*2*Pi and looks like:
#define _PD_CONST(Name, Val) \
static const double _pd_##Name[2] __attribute__((aligned(16))) = { Val, Val }
_PD_CONST(2Pi, 6.283185307179586); /* = 2*pi */
_PD_CONST(recip_2Pi, 0.159154943091895); /* = 1/(2*pi) */
void vec_mod_2pi(const double * vec, int Size, double * modAns)
{
__m128d sse_a, sse_b, sse_c;
int i;
int k = 0;
double t = 0;
unsigned int initial_mode;
initial_mode = _MM_GET_ROUNDING_MODE();
_MM_SET_ROUNDING_MODE(_MM_ROUND_DOWN);
for (i = 0; i < Size; i += 2)
{
sse_a = _mm_loadu_pd(vec+i);
sse_b = _mm_mul_pd( _mm_cvtepi32_pd( _mm_cvtpd_epi32( _mm_mul_pd(sse_a, *(__m128d*)_pd_recip_2Pi) ) ), *(__m128d*)_pd_2Pi);
sse_c = _mm_sub_pd(sse_a, sse_b);
_mm_storeu_pd(modAns+i,sse_c);
}
k = i-2;
for (i = 0; i < Size%2; i++)
{
t = (double)((int)(vec[k+i] * 0.159154943091895)) * 6.283185307179586;
modAns[k+i] = vec[k+i] - t;
}
_MM_SET_ROUNDING_MODE(initial_mode);
}
Unfortunately, this is currently returning a lot of NaN with a couple of answers of 1.128e119 as well (some what outside the range of 0 -> 2*Pi that I was aiming for!). I suspect that where I'm going wrong is in the double-to-int-to-double conversion that I'm trying to use to do the floor.
Can anyone suggest where I've gone wrong and how to improve it?
P.S. sorry about the format of that code, it's the first time I've posted a question on here and can't seem to get it to give me empty lines within the code block to make it readable.
If you want any kind of accuracy, the simple algorithm is terribly bad. For an accurate range reduction algorithm, see e.g. Ng et al., ARGUMENT REDUCTION FOR HUGE ARGUMENTS: Good to the Last Bit (now available via the Wayback Machine: 2012-12-24)
For large arguments Hayne-Panek algorithm is typically used. However, the Hayne-Panek paper is quite difficult to read, and I suggest to have a look at Chapter 11 in the Handbook of Floating-Point Arithmetic for a more accessible explanation.

Computing e^(-j) in C

I need to compute imaginary exponential in C.
As far as I know, there is no complex number library in C. It is possible to get e^x with exp(x) of math.h, but how can I compute the value of e^(-i), where i = sqrt(-1)?
In C99, there is a complex type. Include complex.h; you may need to link with -lm on gcc. Note that Microsoft Visual C does not support complex; if you need to use this compiler, maybe you can sprinkle in some C++ and use the complex template.
I is defined as the imaginary unit, and cexp does exponentiation. Full code example:
#include <complex.h>
#include <stdio.h>
int main() {
complex x = cexp(-I);
printf("%lf + %lfi\n", creal(x), cimag(x));
return 0;
}
See man 7 complex for more information.
Note that exponent of complex number equals:
e^(ix) = cos(x)+i*sin(x)
Then:
e^(-i) = cos(-1)+i*sin(-1)
Using the Euler's Formula you have that e^-i == cos(1) - i*sin(1)
e^-j is just cos(1) - j*sin(1), so you can just generate the real and imaginary parts using real functions.
Just use the cartesian form
if z = m*e^j*(arg);
re(z) = m * cos(arg);
im(z) = m * sin(arg);
Is calling a c++ function a solution for you? The C++ STL has a nice complex-class and boost also has to offer some nice options. Write a function in C++ and declare it "extern C"
extern "C" void myexp(float*, float*);
#include <complex>
using std::complex;
void myexp (float *real, float *img )
{
complex<float> param(*real, *img);
complex<float> result = exp (param);
*real = result.real();
*img = result.imag();
}
Then you can call the function from whatever C-code you rely on ( Ansi-C, C99, ...).
#include <stdio.h>
void myexp(float*, float*);
int main(){
float real = 0.0;
float img = -1.0;
myexp(&real, &img);
printf ("e^-i = %f + i* %f\n", real, img);
return 0;
}
In C++ it can be done directly:
std::exp(std::complex<double>(0, -1));

sequence with and without recursion

I have a sequence.
a1 = 1 - cos(x);
ai = a1 + (-1)^(i-1) * x^(2*i-2) / (2*i-2)!
I need to write this with and without recursion. But it has a different results.
Here is my code: http://codepaste.net/q213q6
I'm going to operate under the assumption that this is homework, if I'm wrong I'll come back and edit this post or repost.
Firstly, you should try to write your factorial function in a tail recursive manner. Though it probably won't make much difference in C, it's good practice.
int helper( int x, int acc ) {
if( x == 0 ) {
return acc;
}
else {
return helper( x - 1, acc * x );
}
}
int factorial( x ) {
helper( x, 1 );
}
Next, you don't generally want to put a loop inside of your recursive functions, that somewhat defeats the point. Think of a recursive call as one iteration with a test and either return or recall.
Since you are performing floating point arithmetic. Different ways of implementation can produce different results.
In your case i can think of one place where losses are incurred
currC = pow(x, 2*i-2);
is not equal to
47: currC = currC * x * x;
For more information,
http://en.wikipedia.org/wiki/Floating_point#Multiplication

Resources