馃悕馃悕馃悕
1
2// ========= Cartesian =========== //
3
4function c_cart_constructor(re, im) {
5 return { re, im };
6}
7
8function c_cart_copy(z) {
9 return { re: z.re, im: z.im };
10}
11
12function c_cart_dot(a, b) {
13 return Math.sqrt(a.re * b.re + a.im * b.im);
14}
15
16function c_cart_sub(a, b) {
17 return {
18 re: a.re - b.re,
19 im: a.im - b.im
20 };
21}
22
23function c_cart_mul(a, b) {
24 return {
25 re: a.re * b.re - a.im * b.im,
26 im: a.re * b.im + a.im * b.re
27 };
28}
29
30function c_cart_add(a, b) {
31 return {
32 re: a.re + b.re,
33 im: a.im + b.im
34 };
35}
36
37function c_cart_mag(z) {
38 return c_cart_dot(z, z);
39}
40
41function c_cart_mag_squared(z) {
42 return z.re * z.re + z.im * z.im;
43}
44
45function c_cart_angle(z) {
46 return Math.atan2(z.im, z.re);
47}
48
49function c_cart_to_polar(z) {
50 return {
51 r: c_cart_mag(z),
52 theta: c_cart_angle(z)
53 };
54}
55
56function c_cart_to_pixel(z, dims, center, scale) {
57 const aspect = dims.x / dims.y;
58 const px = (z.re - center.re) * dims.x / (scale * aspect) + dims.x * 0.5;
59 const py = (z.im - center.im) * dims.y / scale + dims.y * 0.5;
60 return {
61 x: px,
62 y: py
63 };
64}
65
66function c_cart_from_pixel(z, dims, center, scale) {
67 const aspect = dims.x / dims.y;
68 const cx = (z.x - dims.x * 0.5) * scale * aspect / dims.x + center.re;
69 const cy = (z.y - dims.y * 0.5) * scale / dims.y + center.im;
70 return {
71 re: cx,
72 im: cy
73 };
74}
75
76// ========= Polar =========== //
77
78function c_polar_constructor(r, theta) {
79 return { r, theta };
80}
81
82function c_polar_re(z) {
83 return z.r * Math.cos(z.theta);
84}
85
86function c_polar_im(z) {
87 return z.r * Math.sin(z.theta);
88}
89
90function c_polar_to_cart(z) {
91 return {
92 re: c_polar_re(z),
93 im: c_polar_im(z)
94 };
95}
96
97
98window.$complex = {
99 cartesian: {
100 of: c_cart_constructor,
101 dot: c_cart_dot,
102 add: c_cart_add,
103 sub: c_cart_sub,
104 mul: c_cart_mul,
105 mag: c_cart_mag,
106 magSq: c_cart_mag_squared,
107 mod: c_cart_mag,
108 angle: c_cart_angle,
109 arg: c_cart_angle,
110 toPolar: c_cart_to_polar,
111 toPixel: c_cart_to_pixel,
112 fromPixel: c_cart_from_pixel,
113 copy: c_cart_copy
114 },
115
116 polar: {
117 of: c_polar_constructor,
118 im: c_polar_im,
119 y: c_polar_im,
120 re: c_polar_re,
121 x: c_polar_re
122 }
123};
124