Function to convert a Cartesian co-ordinate to polar form.
More...
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
|
#define | _USE_MATH_DEFINES |
| required for MS Visual C
|
|
|
void | to_polar (double x, double y, double *r, double *theta) |
| Function to convert cartesian coordinates to polar. More...
|
|
double | get_rand (double lim1, double lim2) |
| Generate a random number in the given limits. More...
|
|
void | test () |
| Test implementation. More...
|
|
int | main () |
| Main function. More...
|
|
Function to convert a Cartesian co-ordinate to polar form.
◆ get_rand()
double get_rand |
( |
double |
lim1, |
|
|
double |
lim2 |
|
) |
| |
Generate a random number in the given limits.
- Parameters
-
lim1 | lower limit |
lim2 | upper limit |
- Returns
- random number in the given range
90 double r = (double)rand() / RAND_MAX;
91 return (lim2 - lim1) * r + lim1;
◆ main()
Main function.
void test()
Test implementation.
Definition: cartesian_to_polar.c:98
◆ test()
Test implementation.
103 for (
int i = 0; i < NUM_TESTS; i++)
106 printf(
"Test %d.... ", i);
109 printf(
"(%.2g, %.2g).... ", x, y);
111 assert(fabs(r - hypot(x, y)) < 0.01);
112 assert(fabs(theta - atan2(y, x)) < 0.01);
double get_rand(double lim1, double lim2)
Generate a random number in the given limits.
Definition: cartesian_to_polar.c:88
void to_polar(double x, double y, double *r, double *theta)
Function to convert cartesian coordinates to polar.
Definition: cartesian_to_polar.c:22
◆ to_polar()
void to_polar |
( |
double |
x, |
|
|
double |
y, |
|
|
double * |
r, |
|
|
double * |
theta |
|
) |
| |
Function to convert cartesian coordinates to polar.
\begin{eqnarray*} r &=& \sqrt{x^2+y^2}\\ \theta &=& \atan\frac{y}{x} \end{eqnarray*}
- Parameters
-
[in] | x | absicca value |
[in] | y | ordinate value |
[out] | r | pointer to store polar radius |
[out] | theta | pointer to store polar angle (in radian) |
24 double thetaFinal = 0.f;
26 *r = sqrt(x * x + y * y);
33 if ((x > 0 && y > 0) || (x == -y))
37 else if (x < 0 && y > 0)
39 thetaFinal = *theta + M_PI;
41 else if (x < 0 && y < 0)
43 thetaFinal = *theta - M_PI;
45 else if (x > 0 && y < 0)
47 thetaFinal = 2 * M_PI - *theta;
51 fprintf(stderr,
"Should not reach here!\n");
59 thetaFinal = M_PI / 2;
63 thetaFinal = -(M_PI / 2);