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
89{
90 double r = (double)rand() / RAND_MAX;
91 return (lim2 - lim1) * r + lim1;
92}
◆ main()
Main function.
119{
121
122 return 0;
123}
void test()
Test implementation.
Definition: cartesian_to_polar.c:98
◆ test()
Test implementation.
99{
100 srand(10);
101 int NUM_TESTS = 5;
102
103 for (int i = 0; i < NUM_TESTS; i++)
104 {
105 double r, theta;
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);
113 printf("passed\n");
114 }
115}
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) |
23{
24 double thetaFinal = 0.f;
25
26 *r = sqrt(x * x + y * y);
27
28 if (x != 0)
29 {
30 if (y != 0)
31 {
32 *theta = atan(y / x);
33 if ((x > 0 && y > 0) || (x == -y))
34 {
35 thetaFinal = *theta;
36 }
37 else if (x < 0 && y > 0)
38 {
39 thetaFinal = *theta + M_PI;
40 }
41 else if (x < 0 && y < 0)
42 {
43 thetaFinal = *theta - M_PI;
44 }
45 else if (x > 0 && y < 0)
46 {
47 thetaFinal = 2 * M_PI - *theta;
48 }
49 else
50 {
51 fprintf(stderr, "Should not reach here!\n");
52 }
53 }
54 }
55 else
56 {
57 if (y > 0)
58 {
59 thetaFinal = M_PI / 2;
60 }
61 else
62 {
63 thetaFinal = -(M_PI / 2);
64 }
65 }
66 if (y == 0)
67 {
68 if (x > 0)
69 {
70 thetaFinal = 0;
71 }
72 else
73 {
74 thetaFinal = -M_PI;
75 }
76 }
77
78 *theta = thetaFinal;
79}