-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmag.cpp
158 lines (124 loc) · 2.01 KB
/
mag.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
/* Magnitude of complex z
z mag(z)
- ------
a a
-a a
(-1)^a 1
exp(a + i b) exp(a)
a b mag(a) mag(b)
a + i b sqrt(a^2 + b^2)
Notes
1. Handles mixed polar and rectangular forms, e.g. 1 + exp(i pi/3)
2. jean-francois.debroux reports that when z=(a+i*b)/(c+i*d) then
mag(numerator(z)) / mag(denominator(z))
must be used to get the correct answer. Now the operation is
automatic.
*/
#include "stdafx.h"
#include "defs.h"
void
eval_mag(void)
{
push(cadr(p1));
eval();
mag();
}
void
mag(void)
{
save();
p1 = pop();
push(p1);
numerator();
yymag();
push(p1);
denominator();
yymag();
divide();
restore();
}
void
yymag(void)
{
save();
p1 = pop();
if (isnegativenumber(p1)) {
push(p1);
negate();
} else if (car(p1) == symbol(POWER) && equaln(cadr(p1), -1))
// -1 to a power
push_integer(1);
else if (car(p1) == symbol(POWER) && cadr(p1) == symbol(E)) {
// exponential
push(caddr(p1));
real();
exponential();
} else if (car(p1) == symbol(MULTIPLY)) {
// product
push_integer(1);
p1 = cdr(p1);
while (iscons(p1)) {
push(car(p1));
mag();
multiply();
p1 = cdr(p1);
}
} else if (car(p1) == symbol(ADD)) {
// sum
push(p1);
rect(); // convert polar terms, if any
p1 = pop();
push(p1);
real();
push_integer(2);
power();
push(p1);
imag();
push_integer(2);
power();
add();
push_rational(1, 2);
power();
simplify_trig();
} else
// default (all real)
push(p1);
restore();
}
#if SELFTEST
static const char *s[] = {
"mag(a+i*b)",
"(a^2+b^2)^(1/2)",
"mag(exp(a+i*b))",
"exp(a)",
"mag(1)",
"1",
"mag(-1)",
"1",
"mag(1+exp(i*pi/3))",
"3^(1/2)",
"mag((a+i*b)/(c+i*d))",
"(a^2+b^2)^(1/2)/((c^2+d^2)^(1/2))",
"mag(exp(i theta))",
"1",
"mag(exp(-i theta))",
"1",
"mag((-1)^theta)",
"1",
"mag((-1)^(-theta))",
"1",
"mag(3*(-1)^theta)",
"3",
"mag(3*(-1)^(-theta))",
"3",
"mag(-3*(-1)^theta)",
"3",
"mag(-3*(-1)^(-theta))",
"3",
};
void
test_mag(void)
{
test(__FILE__, s, sizeof s / sizeof (char *));
}
#endif