Debian Codegraph @

texk/web2c/mplibdir/mpmath.w

raw
1 % This file is part of MetaPost;
2 % the MetaPost program is in the public domain.
3 % See the <Show version...> code in mpost.w for more info.
4
5 % Here is TeX material that gets inserted after \input webmac
6
7 \font\tenlogo=logo10 % font used for the METAFONT logo
8 \font\logos=logosl10
9 \def\MF{{\tenlogo META}\-{\tenlogo FONT}}
10 \def\MP{{\tenlogo META}\-{\tenlogo POST}}
11 \def\pct!{{\char`\%}} % percent sign in ordinary text
12 \def\psqrt#1{\sqrt{\mathstrut#1}}
13
14 \def\title{Math support functions for 32-bit integer math}
15 \pdfoutput=1
16
17 @ Introduction.
18
19 @c
20 #include "mpconfig.h"
21 #include <w2c/config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <math.h>
26 #include "mpmath.h" /* internal header */
27 @h
28
29 @ @c
30 @<Declarations@>
31
32 @ @(mpmath.h@>=
33 #ifndef MPMATH_H
34 #define MPMATH_H 1
35 #include "mplib.h"
36 #include "mpmp.h" /* internal header */
37 @<Internal library declarations@>
38 #endif
39
40 @* Math initialization.
41
42 @ Here are the functions that are static as they are not used elsewhere
43
44 @<Declarations@>=
45 static void mp_scan_fractional_token (MP mp, integer64 n);
46 static void mp_scan_numeric_token (MP mp, integer64 n);
47 static void mp_ab_vs_cd (MP mp, mp_number *ret, mp_number a, mp_number b, mp_number c, mp_number d);
48 static void mp_crossing_point (MP mp, mp_number *ret, mp_number a, mp_number b, mp_number c);
49 static void mp_number_modulo (mp_number *a, mp_number b);
50 static void mp_print_number (MP mp, mp_number n);
51 static char * mp_number_tostring (MP mp, mp_number n);
52 static void mp_slow_add (MP mp, mp_number *ret, mp_number x_orig, mp_number y_orig);
53 static void mp_square_rt (MP mp, mp_number *ret, mp_number x_orig);
54 static void mp_n_sin_cos (MP mp, mp_number z_orig, mp_number *n_cos, mp_number *n_sin);
55 static void mp_init_randoms (MP mp, int seed);
56 static void mp_number_angle_to_scaled (mp_number *A);
57 static void mp_number_fraction_to_scaled (mp_number *A);
58 static void mp_number_scaled_to_fraction (mp_number *A);
59 static void mp_number_scaled_to_angle (mp_number *A);
60 static void mp_m_unif_rand (MP mp, mp_number *ret, mp_number x_orig);
61 static void mp_m_norm_rand (MP mp, mp_number *ret);
62 static void mp_m_exp (MP mp, mp_number *ret, mp_number x_orig);
63 static void mp_m_log (MP mp, mp_number *ret, mp_number x_orig);
64 static void mp_pyth_sub (MP mp, mp_number *r, mp_number a, mp_number b);
65 static void mp_n_arg (MP mp, mp_number *ret, mp_number x, mp_number y);
66 static void mp_velocity (MP mp, mp_number *ret, mp_number st, mp_number ct, mp_number sf, mp_number cf, mp_number t);
67 static void mp_set_number_from_int(mp_number *A, integer64 B);
68 static void mp_set_number_from_boolean(mp_number *A, integer64 B);
69 static void mp_set_number_from_scaled(mp_number *A, integer64 B);
70 static void mp_set_number_from_boolean(mp_number *A, integer64 B);
71 static void mp_set_number_from_addition(mp_number *A, mp_number B, mp_number C);
72 static void mp_set_number_from_substraction (mp_number *A, mp_number B, mp_number C);
73 static void mp_set_number_from_div(mp_number *A, mp_number B, mp_number C);
74 static void mp_set_number_from_mul(mp_number *A, mp_number B, mp_number C);
75 static void mp_set_number_from_int_div(mp_number *A, mp_number B, integer64 C);
76 static void mp_set_number_from_int_mul(mp_number *A, mp_number B, integer64 C);
77 static void mp_set_number_from_of_the_way(MP mp, mp_number *A, mp_number t, mp_number B, mp_number C);
78 static void mp_number_negate(mp_number *A);
79 static void mp_number_add(mp_number *A, mp_number B);
80 static void mp_number_substract(mp_number *A, mp_number B);
81 static void mp_number_half(mp_number *A);
82 static void mp_number_halfp(mp_number *A);
83 static void mp_number_double(mp_number *A);
84 static void mp_number_add_scaled(mp_number *A, integer64 B); /* also for negative B */
85 static void mp_number_multiply_int(mp_number *A, integer64 B);
86 static void mp_number_divide_int(mp_number *A, integer64 B);
87 static void mp_number_abs(mp_number *A);
88 static void mp_number_clone(mp_number *A, mp_number B);
89 static void mp_number_swap(mp_number *A, mp_number *B);
90 static integer64 mp_round_unscaled(mp_number x_orig);
91 static integer64 mp_number_to_scaled(mp_number A);
92 static integer64 mp_number_to_boolean(mp_number A);
93 static integer64 mp_number_to_int(mp_number A);
94 static int mp_number_odd(mp_number A);
95 static int mp_number_equal(mp_number A, mp_number B);
96 static int mp_number_greater(mp_number A, mp_number B);
97 static int mp_number_less(mp_number A, mp_number B);
98 static int mp_number_nonequalabs(mp_number A, mp_number B);
99 static void mp_number_floor (mp_number *i);
100 static void mp_fraction_to_round_scaled (mp_number *x);
101 static void mp_number_make_scaled (MP mp, mp_number *r, mp_number p, mp_number q);
102 static void mp_number_make_fraction (MP mp, mp_number *r, mp_number p, mp_number q);
103 static void mp_number_take_fraction (MP mp, mp_number *r, mp_number p, mp_number q);
104 static void mp_number_take_scaled (MP mp, mp_number *r, mp_number p, mp_number q);
105 static void mp_new_number (MP mp, mp_number *n, mp_number_type t) ;
106 static void mp_free_number (MP mp, mp_number *n) ;
107 static void mp_free_scaled_math (MP mp);
108 static void mp_scaled_set_precision (MP mp);
109
110 @ And these are the ones that {\it are} used elsewhere
111
112 @<Internal library declarations@>=
113 void * mp_initialize_scaled_math (MP mp);
114 void mp_set_number_from_double(mp_number *A, double B);
115 void mp_pyth_add (MP mp, mp_number *r, mp_number a, mp_number b);
116 double mp_number_to_double(mp_number A);
117
118 @
119
120 @d coef_bound 04525252525 /* |fraction| approximation to 7/3 */
121 @d fraction_threshold 2685 /* a |fraction| coefficient less than this is zeroed */
122 @d half_fraction_threshold 1342 /* half of |fraction_threshold| */
123 @d scaled_threshold 8 /* a |scaled| coefficient less than this is zeroed */
124 @d half_scaled_threshold 4 /* half of |scaled_threshold| */
125 @d near_zero_angle 26844
126 @d p_over_v_threshold 0x80000
127 @d equation_threshold 64
128 @d tfm_warn_threshold 4096
129
130
131 @c
132 void * mp_initialize_scaled_math (MP mp) {
133 math_data *math = (math_data *)mp_xmalloc(mp,1,sizeof(math_data));
134 /* alloc */
135 math->allocate = mp_new_number;
136 math->free = mp_free_number;
137 mp_new_number (mp, &math->precision_default, mp_scaled_type);
138 math->precision_default.data.val = unity * 10;
139 mp_new_number (mp, &math->precision_max, mp_scaled_type);
140 math->precision_max.data.val = unity * 10;
141 mp_new_number (mp, &math->precision_min, mp_scaled_type);
142 math->precision_min.data.val = unity * 10;
143 /* here are the constants for |scaled| objects */
144 mp_new_number (mp, &math->epsilon_t, mp_scaled_type);
145 math->epsilon_t.data.val = 1;
146 mp_new_number (mp, &math->inf_t, mp_scaled_type);
147 math->inf_t.data.val = EL_GORDO;
148 mp_new_number (mp, &math->warning_limit_t, mp_scaled_type);
149 math->warning_limit_t.data.val = fraction_one;
150 mp_new_number (mp, &math->one_third_inf_t, mp_scaled_type);
151 math->one_third_inf_t.data.val = one_third_EL_GORDO;
152 mp_new_number (mp, &math->unity_t, mp_scaled_type);
153 math->unity_t.data.val = unity;
154 mp_new_number (mp, &math->two_t, mp_scaled_type);
155 math->two_t.data.val = two;
156 mp_new_number (mp, &math->three_t, mp_scaled_type);
157 math->three_t.data.val = three;
158 mp_new_number (mp, &math->half_unit_t, mp_scaled_type);
159 math->half_unit_t.data.val = half_unit;
160 mp_new_number (mp, &math->three_quarter_unit_t, mp_scaled_type);
161 math->three_quarter_unit_t.data.val = three_quarter_unit;
162 mp_new_number (mp, &math->zero_t, mp_scaled_type);
163 /* |fractions| */
164 mp_new_number (mp, &math->arc_tol_k, mp_fraction_type);
165 math->arc_tol_k.data.val = (unity/4096); /* quit when change in arc length estimate reaches this */
166 mp_new_number (mp, &math->fraction_one_t, mp_fraction_type);
167 math->fraction_one_t.data.val = fraction_one;
168 mp_new_number (mp, &math->fraction_half_t, mp_fraction_type);
169 math->fraction_half_t.data.val = fraction_half;
170 mp_new_number (mp, &math->fraction_three_t, mp_fraction_type);
171 math->fraction_three_t.data.val = fraction_three;
172 mp_new_number (mp, &math->fraction_four_t, mp_fraction_type);
173 math->fraction_four_t.data.val = fraction_four;
174 /* |angles| */
175 mp_new_number (mp, &math->three_sixty_deg_t, mp_angle_type);
176 math->three_sixty_deg_t.data.val = three_sixty_deg;
177 mp_new_number (mp, &math->one_eighty_deg_t, mp_angle_type);
178 math->one_eighty_deg_t.data.val = one_eighty_deg;
179 /* various approximations */
180 mp_new_number (mp, &math->one_k, mp_scaled_type);
181 math->one_k.data.val = 1024;
182 mp_new_number (mp, &math->sqrt_8_e_k, mp_scaled_type);
183 math->sqrt_8_e_k.data.val = 112429; /* $2^{16}\sqrt{8/e}\approx 112428.82793$ */
184 mp_new_number (mp, &math->twelve_ln_2_k, mp_fraction_type);
185 math->twelve_ln_2_k.data.val = 139548960; /* $2^{24}\cdot12\ln2\approx139548959.6165$ */
186 mp_new_number (mp, &math->coef_bound_k, mp_fraction_type);
187 math->coef_bound_k.data.val = coef_bound;
188 mp_new_number (mp, &math->coef_bound_minus_1, mp_fraction_type);
189 math->coef_bound_minus_1.data.val = coef_bound - 1;
190 mp_new_number (mp, &math->twelvebits_3, mp_scaled_type);
191 math->twelvebits_3.data.val = 1365; /* $1365\approx 2^{12}/3$ */
192 mp_new_number (mp, &math->twentysixbits_sqrt2_t, mp_fraction_type);
193 math->twentysixbits_sqrt2_t.data.val = 94906266; /* $2^{26}\sqrt2\approx94906265.62$ */
194 mp_new_number (mp, &math->twentyeightbits_d_t, mp_fraction_type);
195 math->twentyeightbits_d_t.data.val = 35596755; /* $2^{28}d\approx35596754.69$ */
196 mp_new_number (mp, &math->twentysevenbits_sqrt2_d_t, mp_fraction_type);
197 math->twentysevenbits_sqrt2_d_t.data.val = 25170707; /* $2^{27}\sqrt2\,d\approx25170706.63$ */
198 /* thresholds */
199 mp_new_number (mp, &math->fraction_threshold_t, mp_fraction_type);
200 math->fraction_threshold_t.data.val = fraction_threshold;
201 mp_new_number (mp, &math->half_fraction_threshold_t, mp_fraction_type);
202 math->half_fraction_threshold_t.data.val = half_fraction_threshold;
203 mp_new_number (mp, &math->scaled_threshold_t, mp_scaled_type);
204 math->scaled_threshold_t.data.val = scaled_threshold;
205 mp_new_number (mp, &math->half_scaled_threshold_t, mp_scaled_type);
206 math->half_scaled_threshold_t.data.val = half_scaled_threshold;
207 mp_new_number (mp, &math->near_zero_angle_t, mp_angle_type);
208 math->near_zero_angle_t.data.val = near_zero_angle;
209 mp_new_number (mp, &math->p_over_v_threshold_t, mp_fraction_type);
210 math->p_over_v_threshold_t.data.val = p_over_v_threshold;
211 mp_new_number (mp, &math->equation_threshold_t, mp_scaled_type);
212 math->equation_threshold_t.data.val = equation_threshold;
213 mp_new_number (mp, &math->tfm_warn_threshold_t, mp_scaled_type);
214 math->tfm_warn_threshold_t.data.val = tfm_warn_threshold;
215 /* functions */
216 math->from_int = mp_set_number_from_int;
217 math->from_boolean = mp_set_number_from_boolean;
218 math->from_scaled = mp_set_number_from_scaled;
219 math->from_double = mp_set_number_from_double;
220 math->from_addition = mp_set_number_from_addition;
221 math->from_substraction = mp_set_number_from_substraction;
222 math->from_oftheway = mp_set_number_from_of_the_way;
223 math->from_div = mp_set_number_from_div;
224 math->from_mul = mp_set_number_from_mul;
225 math->from_int_div = mp_set_number_from_int_div;
226 math->from_int_mul = mp_set_number_from_int_mul;
227 math->negate = mp_number_negate;
228 math->add = mp_number_add;
229 math->substract = mp_number_substract;
230 math->half = mp_number_half;
231 math->halfp = mp_number_halfp;
232 math->do_double = mp_number_double;
233 math->abs = mp_number_abs;
234 math->clone = mp_number_clone;
235 math->swap = mp_number_swap;
236 math->add_scaled = mp_number_add_scaled;
237 math->multiply_int = mp_number_multiply_int;
238 math->divide_int = mp_number_divide_int;
239 math->to_int = mp_number_to_int;
240 math->to_boolean = mp_number_to_boolean;
241 math->to_scaled = mp_number_to_scaled;
242 math->to_double = mp_number_to_double;
243 math->odd = mp_number_odd;
244 math->equal = mp_number_equal;
245 math->less = mp_number_less;
246 math->greater = mp_number_greater;
247 math->nonequalabs = mp_number_nonequalabs;
248 math->round_unscaled = mp_round_unscaled;
249 math->floor_scaled = mp_number_floor;
250 math->fraction_to_round_scaled = mp_fraction_to_round_scaled;
251 math->make_scaled = mp_number_make_scaled;
252 math->make_fraction = mp_number_make_fraction;
253 math->take_fraction = mp_number_take_fraction;
254 math->take_scaled = mp_number_take_scaled;
255 math->velocity = mp_velocity;
256 math->n_arg = mp_n_arg;
257 math->m_log = mp_m_log;
258 math->m_exp = mp_m_exp;
259 math->m_unif_rand = mp_m_unif_rand;
260 math->m_norm_rand = mp_m_norm_rand;
261 math->pyth_add = mp_pyth_add;
262 math->pyth_sub = mp_pyth_sub;
263 math->fraction_to_scaled = mp_number_fraction_to_scaled;
264 math->scaled_to_fraction = mp_number_scaled_to_fraction;
265 math->scaled_to_angle = mp_number_scaled_to_angle;
266 math->angle_to_scaled = mp_number_angle_to_scaled;
267 math->init_randoms = mp_init_randoms;
268 math->sin_cos = mp_n_sin_cos;
269 math->slow_add = mp_slow_add;
270 math->sqrt = mp_square_rt;
271 math->print = mp_print_number;
272 math->tostring = mp_number_tostring;
273 math->modulo = mp_number_modulo;
274 math->ab_vs_cd = mp_ab_vs_cd;
275 math->crossing_point = mp_crossing_point;
276 math->scan_numeric = mp_scan_numeric_token;
277 math->scan_fractional = mp_scan_fractional_token;
278 math->free_math = mp_free_scaled_math;
279 math->set_precision = mp_scaled_set_precision;
280 return (void *)math;
281 }
282
283 void mp_scaled_set_precision (MP mp) {
284 (void)mp;
285 }
286
287 void mp_free_scaled_math (MP mp) {
288 free_number (((math_data *)mp->math)->epsilon_t);
289 free_number (((math_data *)mp->math)->inf_t);
290 free_number (((math_data *)mp->math)->arc_tol_k);
291 free_number (((math_data *)mp->math)->three_sixty_deg_t);
292 free_number (((math_data *)mp->math)->one_eighty_deg_t);
293 free_number (((math_data *)mp->math)->fraction_one_t);
294 free_number (((math_data *)mp->math)->fraction_half_t);
295 free_number (((math_data *)mp->math)->fraction_three_t);
296 free_number (((math_data *)mp->math)->fraction_four_t);
297 free_number (((math_data *)mp->math)->zero_t);
298 free_number (((math_data *)mp->math)->half_unit_t);
299 free_number (((math_data *)mp->math)->three_quarter_unit_t);
300 free_number (((math_data *)mp->math)->unity_t);
301 free_number (((math_data *)mp->math)->two_t);
302 free_number (((math_data *)mp->math)->three_t);
303 free_number (((math_data *)mp->math)->one_third_inf_t);
304 free_number (((math_data *)mp->math)->warning_limit_t);
305 free_number (((math_data *)mp->math)->one_k);
306 free_number (((math_data *)mp->math)->sqrt_8_e_k);
307 free_number (((math_data *)mp->math)->twelve_ln_2_k);
308 free_number (((math_data *)mp->math)->coef_bound_k);
309 free_number (((math_data *)mp->math)->coef_bound_minus_1);
310 free_number (((math_data *)mp->math)->twelvebits_3);
311 free_number (((math_data *)mp->math)->twentysixbits_sqrt2_t);
312 free_number (((math_data *)mp->math)->twentyeightbits_d_t);
313 free_number (((math_data *)mp->math)->twentysevenbits_sqrt2_d_t);
314 free_number (((math_data *)mp->math)->fraction_threshold_t);
315 free_number (((math_data *)mp->math)->half_fraction_threshold_t);
316 free_number (((math_data *)mp->math)->scaled_threshold_t);
317 free_number (((math_data *)mp->math)->half_scaled_threshold_t);
318 free_number (((math_data *)mp->math)->near_zero_angle_t);
319 free_number (((math_data *)mp->math)->p_over_v_threshold_t);
320 free_number (((math_data *)mp->math)->equation_threshold_t);
321 free_number (((math_data *)mp->math)->tfm_warn_threshold_t);
322 free(mp->math);
323 }
324
325 @ Creating an destroying |mp_number| objects
326
327 @ @c
328 void mp_new_number (MP mp, mp_number *n, mp_number_type t) {
329 (void)mp;
330 n->data.val = 0;
331 n->type = t;
332 }
333
334 @
335 @c
336 void mp_free_number (MP mp, mp_number *n) {
337 (void)mp;
338 n->type = mp_nan_type;
339 }
340
341 @ Here are the low-level functions on |mp_number| items, setters first.
342
343 @c
344 void mp_set_number_from_int(mp_number *A, integer64 B) {
345 A->data.val = B;
346 }
347 void mp_set_number_from_boolean(mp_number *A, integer64 B) {
348 A->data.val = B;
349 }
350 void mp_set_number_from_scaled(mp_number *A, integer64 B) {
351 A->data.val = B;
352 }
353 void mp_set_number_from_double(mp_number *A, double B) {
354 A->data.val = (int)(B*65536.0);
355 }
356 void mp_set_number_from_addition(mp_number *A, mp_number B, mp_number C) {
357 A->data.val = B.data.val+C.data.val;
358 }
359 void mp_set_number_from_substraction (mp_number *A, mp_number B, mp_number C) {
360 A->data.val = B.data.val-C.data.val;
361 }
362 void mp_set_number_from_div(mp_number *A, mp_number B, mp_number C) {
363 A->data.val = B.data.val / C.data.val;
364 }
365 void mp_set_number_from_mul(mp_number *A, mp_number B, mp_number C) {
366 A->data.val = B.data.val * C.data.val;
367 }
368 void mp_set_number_from_int_div(mp_number *A, mp_number B, integer64 C) {
369 A->data.val = B.data.val / C;
370 }
371 void mp_set_number_from_int_mul(mp_number *A, mp_number B, integer64 C) {
372 A->data.val = B.data.val * C;
373 }
374 void mp_set_number_from_of_the_way(MP mp, mp_number *A, mp_number t, mp_number B, mp_number C) {
375 A->data.val = B.data.val - mp_take_fraction(mp, (B.data.val - C.data.val), t.data.val);
376 }
377 void mp_number_negate(mp_number *A) {
378 A->data.val = -A->data.val;
379 }
380 void mp_number_add(mp_number *A, mp_number B) {
381 A->data.val = A->data.val + B.data.val;
382 }
383 void mp_number_substract(mp_number *A, mp_number B) {
384 A->data.val = A->data.val - B.data.val;
385 }
386 void mp_number_half(mp_number *A) {
387 A->data.val = A->data.val/2;
388 }
389 void mp_number_halfp(mp_number *A) {
390 A->data.val = (A->data.val>>1);
391 }
392 void mp_number_double(mp_number *A) {
393 A->data.val = A->data.val + A->data.val;
394 }
395 void mp_number_add_scaled(mp_number *A, integer64 B) { /* also for negative B */
396 A->data.val = A->data.val + B;
397 }
398 void mp_number_multiply_int(mp_number *A, integer64 B) {
399 A->data.val = B * A->data.val;
400 }
401 void mp_number_divide_int(mp_number *A, integer64 B) {
402 A->data.val = A->data.val / B;
403 }
404 void mp_number_abs(mp_number *A) {
405 A->data.val = MPOST_ABS(A->data.val);
406 }
407 void mp_number_clone(mp_number *A, mp_number B) {
408 A->data.val = B.data.val;
409 }
410 void mp_number_swap(mp_number *A, mp_number *B) {
411 integer64 swap_tmp = A->data.val;
412 A->data.val = B->data.val;
413 B->data.val = swap_tmp;
414 }
415 void mp_number_fraction_to_scaled (mp_number *A) {
416 A->type = mp_scaled_type;
417 A->data.val = A->data.val / 4096;
418 }
419 void mp_number_angle_to_scaled (mp_number *A) {
420 A->type = mp_scaled_type;
421 if (A->data.val >= 0) {
422 A->data.val = (A->data.val + 8) / 16;
423 } else {
424 A->data.val = -((-A->data.val + 8) / 16);
425 }
426 }
427 void mp_number_scaled_to_fraction (mp_number *A) {
428 A->type = mp_fraction_type;
429 A->data.val = A->data.val * 4096;
430 }
431 void mp_number_scaled_to_angle (mp_number *A) {
432 A->type = mp_angle_type;
433 A->data.val = A->data.val * 16;
434 }
435
436
437 @ Query functions
438
439 @c
440 integer64 mp_number_to_int(mp_number A) {
441 return A.data.val;
442 }
443 integer64 mp_number_to_scaled(mp_number A) {
444 return A.data.val;
445 }
446 integer64 mp_number_to_boolean(mp_number A) {
447 return A.data.val;
448 }
449 double mp_number_to_double(mp_number A) {
450 return ((double)A.data.val/65536.0);
451 }
452 int mp_number_odd(mp_number A) {
453 return odd(A.data.val);
454 }
455 int mp_number_equal(mp_number A, mp_number B) {
456 return (A.data.val==B.data.val);
457 }
458 int mp_number_greater(mp_number A, mp_number B) {
459 return (A.data.val>B.data.val);
460 }
461 int mp_number_less(mp_number A, mp_number B) {
462 return (A.data.val<B.data.val);
463 }
464 int mp_number_nonequalabs(mp_number A, mp_number B) {
465 return (!(MPOST_ABS(A.data.val)==MPOST_ABS(B.data.val)));
466 }
467
468 @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
469 of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
470 positions from the right end of a binary computer word.
471
472 @d unity (mpinteger64)(0x10000) /* $2^{16}$, represents 1.00000 */
473 @d two (2*unity) /* $2^{17}$, represents 2.00000 */
474 @d three (3*unity) /* $2^{17}+2^{16}$, represents 3.00000 */
475 @d half_unit (unity/2) /* $2^{15}$, represents 0.50000 */
476 @d three_quarter_unit (3*(unity/4)) /* $3\cdot2^{14}$, represents 0.75000 */
477
478 @d EL_GORDO (mpinteger64)(0x7fffffff) /* $2^{31}-1$, the largest value that \MP\ likes */
479 @d one_third_EL_GORDO (mpinteger64)(05252525252)
480
481 @ One of \MP's most common operations is the calculation of
482 $\lfloor{a+b\over2}\rfloor$,
483 the midpoint of two given integers |a| and~|b|. The most decent way to do
484 this is to write `|(a+b)/2|'; but on many machines it is more efficient
485 to calculate `|(a+b)>>1|'.
486
487 Therefore the midpoint operation will always be denoted by `|half(a+b)|'
488 in this program. If \MP\ is being implemented with languages that permit
489 binary shifting, the |half| macro should be changed to make this operation
490 as efficient as possible. Since some systems have shift operators that can
491 only be trusted to work on positive numbers, there is also a macro |halfp|
492 that is used only when the quantity being halved is known to be positive
493 or zero.
494
495 @d halfp(A) (mpinteger64)((unsigned)(A) >> 1)
496
497 @ Here is a procedure analogous to |print_int|. If the output
498 of this procedure is subsequently read by \MP\ and converted by the
499 |round_decimals| routine above, it turns out that the original value will
500 be reproduced exactly. A decimal point is printed only if the value is
501 not an integer. If there is more than one way to print the result with
502 the optimum number of digits following the decimal point, the closest
503 possible value is given.
504
505 The invariant relation in the \&{repeat} loop is that a sequence of
506 decimal digits yet to be printed will yield the original number if and only if
507 they form a fraction~$f$ in the range $s-\delta\L10\cdot2^{16}f<s$.
508 We can stop if and only if $f=0$ satisfies this condition; the loop will
509 terminate before $s$ can possibly become zero.
510
511 @<Declarations@>=
512 static void mp_print_scaled (MP mp, integer64 s); /* scaled */
513 static char *mp_string_scaled (MP mp, integer64 s);
514
515 @ @c
516 static void mp_print_scaled (MP mp, integer64 s) { /* s=scaled prints scaled real, rounded to five digits */
517 integer64 delta; /* amount of allowable inaccuracy, scaled */
518 if (s < 0) {
519 mp_print_char (mp, xord ('-'));
520 s = -s; /* print the sign, if negative */
521 }
522 mp_print_int (mp, s / unity); /* print the integer part */
523 s = 10 * (s % unity) + 5;
524 if (s != 5) {
525 delta = 10;
526 mp_print_char (mp, xord ('.'));
527 do {
528 if (delta > unity)
529 s = s + 0100000 - (delta / 2); /* round the final digit */
530 mp_print_char (mp, xord ('0' + (s / unity)));
531 s = 10 * (s % unity);
532 delta = delta * 10;
533 } while (s > delta);
534 }
535 }
536
537 static char *mp_string_scaled (MP mp, integer64 s) { /* s=scaled prints scaled real, rounded to five digits */
538 static char scaled_string[64];
539 integer64 delta; /* amount of allowable inaccuracy, scaled */
540 int i = 0;
541 if (s < 0) {
542 scaled_string[i++] = xord ('-');
543 s = -s; /* print the sign, if negative */
544 }
545 /* print the integer part */
546 mp_snprintf ((scaled_string+i), 12, "%" PRId64, (s / unity));
547 while (*(scaled_string+i)) i++;
548
549 s = 10 * (s % unity) + 5;
550 if (s != 5) {
551 delta = 10;
552 scaled_string[i++] = xord ('.');
553 do {
554 if (delta > unity)
555 s = s + 0100000 - (delta / 2); /* round the final digit */
556 scaled_string[i++] = xord ('0' + (s / unity));
557 s = 10 * (s % unity);
558 delta = delta * 10;
559 } while (s > delta);
560 }
561 scaled_string[i] = '\0';
562 return scaled_string;
563 }
564
565 @ Addition is not always checked to make sure that it doesn't overflow,
566 but in places where overflow isn't too unlikely the |slow_add| routine
567 is used.
568
569 @c
570 void mp_slow_add (MP mp, mp_number *ret, mp_number x_orig, mp_number y_orig) {
571 mpinteger64 x, y;
572 x = x_orig.data.val;
573 y = y_orig.data.val;
574 if (x >= 0) {
575 if (y <= EL_GORDO - x) {
576 ret->data.val = x + y;
577 } else {
578 mp->arith_error = true;
579 ret->data.val = EL_GORDO;
580 }
581 } else if (-y <= EL_GORDO + x) {
582 ret->data.val = x + y;
583 } else {
584 mp->arith_error = true;
585 ret->data.val = -EL_GORDO;
586 }
587 }
588
589 @ The |make_fraction| routine produces the |fraction| equivalent of
590 |p/q|, given integers |p| and~|q|; it computes the integer
591 $f=\lfloor2^{28}p/q+{1\over2}\rfloor$, when $p$ and $q$ are
592 positive. If |p| and |q| are both of the same scaled type |t|,
593 the ``type relation'' |make_fraction(t,t)=fraction| is valid;
594 and it's also possible to use the subroutine ``backwards,'' using
595 the relation |make_fraction(t,fraction)=t| between scaled types.
596
597 If the result would have magnitude $2^{31}$ or more, |make_fraction|
598 sets |arith_error:=true|. Most of \MP's internal computations have
599 been designed to avoid this sort of error.
600
601 If this subroutine were programmed in assembly language on a typical
602 machine, we could simply compute |(@t$2^{28}$@>*p)div q|, since a
603 double-precision product can often be input to a fixed-point division
604 instruction. But when we are restricted to int-eger arithmetic it
605 is necessary either to resort to multiple-precision maneuvering
606 or to use a simple but slow iteration. The multiple-precision technique
607 would be about three times faster than the code adopted here, but it
608 would be comparatively long and tricky, involving about sixteen
609 additional multiplications and divisions.
610
611 This operation is part of \MP's ``inner loop''; indeed, it will
612 consume nearly 10\pct! of the running time (exclusive of input and output)
613 if the code below is left unchanged. A machine-dependent recoding
614 will therefore make \MP\ run faster. The present implementation
615 is highly portable, but slow; it avoids multiplication and division
616 except in the initial stage. System wizards should be careful to
617 replace it with a routine that is guaranteed to produce identical
618 results in all cases.
619 @^system dependencies@>
620
621 As noted below, a few more routines should also be replaced by machine-dependent
622 code, for efficiency. But when a procedure is not part of the ``inner loop,''
623 such changes aren't advisable; simplicity and robustness are
624 preferable to trickery, unless the cost is too high.
625 @^inner loop@>
626
627 @ We need these preprocessor values
628
629 @d TWEXP31 2147483648.0
630 @d TWEXP28 268435456.0
631 @d TWEXP16 65536.0
632 @d TWEXP_16 (1.0/65536.0)
633 @d TWEXP_28 (1.0/268435456.0)
634
635
636 @c
637 static mpinteger64 mp_make_fraction (MP mp, mpinteger64 p, mpinteger64 q) {
638 mpinteger64 i;
639 if (q == 0)
640 mp_confusion (mp, "/");
641 @:this can't happen /}{\quad \./@>
642 {
643 register double d;
644 d = TWEXP28 * (double) p / (double) q;
645 if ((p ^ q) >= 0) {
646 d += 0.5;
647 if (d >= TWEXP31) {
648 mp->arith_error = true;
649 i = EL_GORDO;
650 goto RETURN;
651 }
652 i = (mpinteger64) d;
653 if (d == (double) i && (((q > 0 ? -q : q) & 077777)
654 * (((i & 037777) << 1) - 1) & 04000) != 0)
655 --i;
656 } else {
657 d -= 0.5;
658 if (d <= -TWEXP31) {
659 mp->arith_error = true;
660 i = -EL_GORDO;
661 goto RETURN;
662 }
663 i = (mpinteger64) d;
664 if (d == (double) i && (((q > 0 ? q : -q) & 077777)
665 * (((i & 037777) << 1) + 1) & 04000) != 0)
666 ++i;
667 }
668 }
669 RETURN:
670 return i;
671 }
672 void mp_number_make_fraction (MP mp, mp_number *ret, mp_number p, mp_number q) {
673 ret->data.val = mp_make_fraction (mp, p.data.val, q.data.val);
674 }
675
676
677 @ The dual of |make_fraction| is |take_fraction|, which multiplies a
678 given integer~|q| by a fraction~|f|. When the operands are positive, it
679 computes $p=\lfloor qf/2^{28}+{1\over2}\rfloor$, a symmetric function
680 of |q| and~|f|.
681
682 This routine is even more ``inner loopy'' than |make_fraction|;
683 the present implementation consumes almost 20\pct! of \MP's computation
684 time during typical jobs, so a machine-language substitute is advisable.
685 @^inner loop@> @^system dependencies@>
686
687 @<Internal library declarations@>=
688 /* still in use by tfmin.w */
689 mpinteger64 mp_take_fraction (MP mp, mpinteger64 q, integer64 f);
690
691 @ @c
692 mpinteger64 mp_take_fraction (MP mp, mpinteger64 p, integer64 q) { /* q = fraction */
693 register double d;
694 register mpinteger64 i;
695 d = (double) p *(double) q *TWEXP_28;
696 if ((p ^ q) >= 0) {
697 d += 0.5;
698 if (d >= TWEXP31) {
699 if (d != TWEXP31 || (((p & 077777) * (q & 077777)) & 040000) == 0)
700 mp->arith_error = true;
701 return EL_GORDO;
702 }
703 i = (mpinteger64) d;
704 if (d == (double) i && (((p & 077777) * (q & 077777)) & 040000) != 0)
705 --i;
706 } else {
707 d -= 0.5;
708 if (d <= -TWEXP31) {
709 if (d != -TWEXP31 || ((-(p & 077777) * (q & 077777)) & 040000) == 0)
710 mp->arith_error = true;
711 return -EL_GORDO;
712 }
713 i = (mpinteger64) d;
714 if (d == (double) i && ((-(p & 077777) * (q & 077777)) & 040000) != 0)
715 ++i;
716 }
717 return i;
718 }
719 void mp_number_take_fraction (MP mp, mp_number *ret, mp_number p_orig, mp_number q_orig) {
720 ret->data.val = mp_take_fraction (mp, p_orig.data.val, q_orig.data.val);
721 }
722
723
724 @ When we want to multiply something by a |scaled| quantity, we use a scheme
725 analogous to |take_fraction| but with a different scaling.
726 Given positive operands, |take_scaled|
727 computes the quantity $p=\lfloor qf/2^{16}+{1\over2}\rfloor$.
728
729 Once again it is a good idea to use a machine-language replacement if
730 possible; otherwise |take_scaled| will use more than 2\pct! of the running time
731 when the Computer Modern fonts are being generated.
732 @^inner loop@>
733
734 @<Declarations@>=
735 static mpinteger64 mp_take_scaled (MP mp, mpinteger64 q, integer64 f);
736
737 @ @c
738 static mpinteger64 mp_take_scaled (MP mp, mpinteger64 p, integer64 q) { /* q = scaled */
739 register double d;
740 register mpinteger64 i;
741 d = (double) p *(double) q *TWEXP_16;
742 if ((p ^ q) >= 0) {
743 d += 0.5;
744 if (d >= TWEXP31) {
745 if (d != TWEXP31 || (((p & 077777) * (q & 077777)) & 040000) == 0)
746 mp->arith_error = true;
747 return EL_GORDO;
748 }
749 i = (mpinteger64) d;
750 if (d == (double) i && (((p & 077777) * (q & 077777)) & 040000) != 0)
751 --i;
752 } else {
753 d -= 0.5;
754 if (d <= -TWEXP31) {
755 if (d != -TWEXP31 || ((-(p & 077777) * (q & 077777)) & 040000) == 0)
756 mp->arith_error = true;
757 return -EL_GORDO;
758 }
759 i = (mpinteger64) d;
760 if (d == (double) i && ((-(p & 077777) * (q & 077777)) & 040000) != 0)
761 ++i;
762 }
763 return i;
764 }
765 void mp_number_take_scaled (MP mp, mp_number *ret, mp_number p_orig, mp_number q_orig) {
766 ret->data.val = mp_take_scaled (mp, p_orig.data.val, q_orig.data.val);
767 }
768
769
770 @ For completeness, there's also |make_scaled|, which computes a
771 quotient as a |scaled| number instead of as a |fraction|.
772 In other words, the result is $\lfloor2^{16}p/q+{1\over2}\rfloor$, if the
773 operands are positive. \ (This procedure is not used especially often,
774 so it is not part of \MP's inner loop.)
775
776 @<Internal library ...@>=
777 /* still in use by svgout.w */
778 integer64 mp_make_scaled (MP mp, mpinteger64 p, mpinteger64 q);
779
780 @ @c
781 integer64 mp_make_scaled (MP mp, mpinteger64 p, mpinteger64 q) { /* return scaled */
782 register mpinteger64 i;
783 if (q == 0)
784 mp_confusion (mp, "/");
785 @:this can't happen /}{\quad \./@> {
786 register double d;
787 d = TWEXP16 * (double) p / (double) q;
788 if ((p ^ q) >= 0) {
789 d += 0.5;
790 if (d >= TWEXP31) {
791 mp->arith_error = true;
792 return EL_GORDO;
793 }
794 i = (mpinteger64) d;
795 if (d == (double) i && (((q > 0 ? -q : q) & 077777)
796 * (((i & 037777) << 1) - 1) & 04000) != 0)
797 --i;
798 } else {
799 d -= 0.5;
800 if (d <= -TWEXP31) {
801 mp->arith_error = true;
802 return -EL_GORDO;
803 }
804 i = (mpinteger64) d;
805 if (d == (double) i && (((q > 0 ? q : -q) & 077777)
806 * (((i & 037777) << 1) + 1) & 04000) != 0)
807 ++i;
808 }
809 }
810 return i;
811 }
812 void mp_number_make_scaled (MP mp, mp_number *ret, mp_number p_orig, mp_number q_orig) {
813 ret->data.val = mp_make_scaled (mp, p_orig.data.val, q_orig.data.val);
814 }
815
816 @ The following function is used to create a scaled integer from a given decimal
817 fraction $(.d_0d_1\ldots d_{k-1})$, where |0<=k<=17|.
818
819 @<Declarations@>=
820 static integer64 mp_round_decimals (MP mp, unsigned char *b, quarterword k);
821
822 @ @c
823 static integer64 mp_round_decimals (MP mp, unsigned char *b, quarterword k) { /* return: scaled */
824 /* converts a decimal fraction */
825 unsigned a = 0; /* the accumulator */
826 int l = 0;
827 (void)mp; /* Will be needed later */
828 for ( l = k-1; l >= 0; l-- ) {
829 if (l<16) /* digits for |k>=17| cannot affect the result */
830 a = (a + (unsigned) (*(b+l) - '0') * two) / 10;
831 }
832 return (integer64) halfp (a + 1);
833 }
834
835 @* Scanning numbers in the input.
836
837 The definitions below are temporarily here.
838
839 @d set_cur_cmd(A) mp->cur_mod_->type=(A)
840 @d set_cur_mod(A) mp->cur_mod_->data.n.data.val=(A)
841
842 @<Declarations...@>=
843 static void mp_wrapup_numeric_token(MP mp, integer64 n, integer64 f);
844
845 @ @c
846 static void mp_wrapup_numeric_token(MP mp, integer64 n, integer64 f) { /* n,f: scaled */
847 integer64 mod ; /* scaled */
848 if (n < 32768) {
849 mod = (n * unity + f);
850 set_cur_mod(mod);
851 if (mod >= fraction_one) {
852 if (internal_value (mp_warning_check).data.val > 0 &&
853 (mp->scanner_status != tex_flushing)) {
854 char msg[256];
855 const char *hlp[] = {"It is at least 4096. Continue and I'll try to cope",
856 "with that big value; but it might be dangerous.",
857 "(Set warningcheck:=0 to suppress this message.)",
858 NULL };
859 mp_snprintf (msg, 256, "Number is too large (%s)", mp_string_scaled(mp,mod));
860 @.Number is too large@>;
861 mp_error (mp, msg, hlp, true);
862 }
863 }
864 } else if (mp->scanner_status != tex_flushing) {
865 const char *hlp[] = {"I can\'t handle numbers bigger than 32767.99998;",
866 "so I've changed your constant to that maximum amount.",
867 NULL };
868 mp_error (mp, "Enormous number has been reduced", hlp, false);
869 @.Enormous number...@>;
870 set_cur_mod(EL_GORDO);
871 }
872 set_cur_cmd((mp_variable_type)mp_numeric_token);
873 }
874
875 @ @c
876 void mp_scan_fractional_token (MP mp, integer64 n) { /* n: scaled */
877 integer64 f; /* scaled */
878 int k = 0;
879 do {
880 k++;
881 mp->cur_input.loc_field++;
882 } while (mp->char_class[mp->buffer[mp->cur_input.loc_field]] == digit_class);
883 f = mp_round_decimals (mp, (unsigned char *)(mp->buffer+mp->cur_input.loc_field-k), (quarterword) k);
884 if (f == unity) {
885 n++;
886 f = 0;
887 }
888 mp_wrapup_numeric_token(mp, n, f);
889 }
890
891
892 @ @c
893 void mp_scan_numeric_token (MP mp, integer64 n) { /* n: scaled */
894 while (mp->char_class[mp->buffer[mp->cur_input.loc_field]] == digit_class) {
895 if (n < 32768)
896 n = 10 * n + mp->buffer[mp->cur_input.loc_field] - '0';
897 mp->cur_input.loc_field++;
898 }
899 if (!(mp->buffer[mp->cur_input.loc_field] == '.' &&
900 mp->char_class[mp->buffer[mp->cur_input.loc_field + 1]] == digit_class)) {
901 mp_wrapup_numeric_token(mp, n, 0);
902 } else {
903 mp->cur_input.loc_field++;
904 mp_scan_fractional_token(mp, n);
905 }
906 }
907
908 @ The |scaled| quantities in \MP\ programs are generally supposed to be
909 less than $2^{12}$ in absolute value, so \MP\ does much of its internal
910 arithmetic with 28~significant bits of precision. A |fraction| denotes
911 a scaled integer whose binary point is assumed to be 28 bit positions
912 from the right.
913
914 @d fraction_half 01000000000 /* $2^{27}$, represents 0.50000000 */
915 @d fraction_one 02000000000 /* $2^{28}$, represents 1.00000000 */
916 @d fraction_two 04000000000 /* $2^{29}$, represents 2.00000000 */
917 @d fraction_three 06000000000 /* $3\cdot2^{28}$, represents 3.00000000 */
918 @d fraction_four 010000000000 /* $2^{30}$, represents 4.00000000 */
919
920 @ Here is a typical example of how the routines above can be used.
921 It computes the function
922 $${1\over3\tau}f(\theta,\phi)=
923 {\tau^{-1}\bigl(2+\sqrt2\,(\sin\theta-{1\over16}\sin\phi)
924 (\sin\phi-{1\over16}\sin\theta)(\cos\theta-\cos\phi)\bigr)\over
925 3\,\bigl(1+{1\over2}(\sqrt5-1)\cos\theta+{1\over2}(3-\sqrt5\,)\cos\phi\bigr)},$$
926 where $\tau$ is a |scaled| ``tension'' parameter. This is \MP's magic
927 fudge factor for placing the first control point of a curve that starts
928 at an angle $\theta$ and ends at an angle $\phi$ from the straight path.
929 (Actually, if the stated quantity exceeds 4, \MP\ reduces it to~4.)
930
931 The trigonometric quantity to be multiplied by $\sqrt2$ is less than $\sqrt2$.
932 (It's a sum of eight terms whose absolute values can be bounded using
933 relations such as $\sin\theta\cos\theta\L{1\over2}$.) Thus the numerator
934 is positive; and since the tension $\tau$ is constrained to be at least
935 $3\over4$, the numerator is less than $16\over3$. The denominator is
936 nonnegative and at most~6. Hence the fixed-point calculations below
937 are guaranteed to stay within the bounds of a 32-bit computer word.
938
939 The angles $\theta$ and $\phi$ are given implicitly in terms of |fraction|
940 arguments |st|, |ct|, |sf|, and |cf|, representing $\sin\theta$, $\cos\theta$,
941 $\sin\phi$, and $\cos\phi$, respectively.
942
943 @c
944 void mp_velocity (MP mp, mp_number *ret, mp_number st, mp_number ct, mp_number sf,
945 mp_number cf, mp_number t) {
946 mpinteger64 acc, num, denom; /* registers for intermediate calculations */
947 acc = mp_take_fraction (mp, st.data.val - (sf.data.val / 16), sf.data.val - (st.data.val / 16));
948 acc = mp_take_fraction (mp, acc, ct.data.val - cf.data.val);
949 num = fraction_two + mp_take_fraction (mp, acc, 379625062);
950 /* $2^{28}\sqrt2\approx379625062.497$ */
951 denom =
952 fraction_three + mp_take_fraction (mp, ct.data.val,
953 497706707) + mp_take_fraction (mp, cf.data.val,
954 307599661);
955 /* $3\cdot2^{27}\cdot(\sqrt5-1)\approx497706706.78$ and
956 $3\cdot2^{27}\cdot(3-\sqrt5\,)\approx307599661.22$ */
957 if (t.data.val != unity)
958 num = mp_make_scaled (mp, num, t.data.val); /* |make_scaled(fraction,scaled)=fraction| */
959 if (num / 4 >= denom) {
960 ret->data.val = fraction_four;
961 } else {
962 ret->data.val = mp_make_fraction (mp, num, denom);
963 }
964 /* |printf ("num,denom=%f,%f -=> %f\n", num/65536.0, denom/65536.0, ret.data.val/65536.0);|*/
965 }
966
967
968 @ The following somewhat different subroutine tests rigorously if $ab$ is
969 greater than, equal to, or less than~$cd$,
970 given integers $(a,b,c,d)$. In most cases a quick decision is reached.
971 The result is $+1$, 0, or~$-1$ in the three respective cases.
972
973 @c
974 static void mp_ab_vs_cd (MP mp, mp_number *ret, mp_number a_orig, mp_number b_orig, mp_number c_orig, mp_number d_orig) {
975 mpinteger64 q, r; /* temporary registers */
976 mpinteger64 a, b, c, d;
977 (void)mp;
978 a = a_orig.data.val;
979 b = b_orig.data.val;
980 c = c_orig.data.val;
981 d = d_orig.data.val;
982 @<Reduce to the case that |a,c>=0|, |b,d>0|@>;
983 while (1) {
984 q = a / d;
985 r = c / b;
986 if (q != r) {
987 ret->data.val = (q > r ? 1 : -1);
988 return;
989 }
990 q = a % d;
991 r = c % b;
992 if (r == 0) {
993 ret->data.val = (q ? 1 : 0);
994 return;
995 }
996 if (q == 0) {
997 ret->data.val = -1;
998 return;
999 }
1000 a = b;
1001 b = q;
1002 c = d;
1003 d = r;
1004 } /* now |a>d>0| and |c>b>0| */
1005 }
1006
1007
1008 @ @<Reduce to the case that |a...@>=
1009 if (a < 0) {
1010 a = -a;
1011 b = -b;
1012 }
1013 if (c < 0) {
1014 c = -c;
1015 d = -d;
1016 }
1017 if (d <= 0) {
1018 if (b >= 0) {
1019 if ((a == 0 || b == 0) && (c == 0 || d == 0))
1020 ret->data.val = 0;
1021 else
1022 ret->data.val = 1;
1023 return;
1024 }
1025 if (d == 0) {
1026 ret->data.val = (a == 0 ? 0 : -1);
1027 return;
1028 }
1029 q = a;
1030 a = c;
1031 c = q;
1032 q = -b;
1033 b = -d;
1034 d = q;
1035 } else if (b <= 0) {
1036 if (b < 0 && a > 0) {
1037 ret->data.val = -1;
1038 return;
1039 }
1040 ret->data.val = (c == 0 ? 0 : -1);
1041 return;
1042 }
1043
1044 @ Now here's a subroutine that's handy for all sorts of path computations:
1045 Given a quadratic polynomial $B(a,b,c;t)$, the |crossing_point| function
1046 returns the unique |fraction| value |t| between 0 and~1 at which
1047 $B(a,b,c;t)$ changes from positive to negative, or returns
1048 |t=fraction_one+1| if no such value exists. If |a<0| (so that $B(a,b,c;t)$
1049 is already negative at |t=0|), |crossing_point| returns the value zero.
1050
1051 The general bisection method is quite simple when $n=2$, hence
1052 |crossing_point| does not take much time. At each stage in the
1053 recursion we have a subinterval defined by |l| and~|j| such that
1054 $B(a,b,c;2^{-l}(j+t))=B(x_0,x_1,x_2;t)$, and we want to ``zero in'' on
1055 the subinterval where $x_0\G0$ and $\min(x_1,x_2)<0$.
1056
1057 It is convenient for purposes of calculation to combine the values
1058 of |l| and~|j| in a single variable $d=2^l+j$, because the operation
1059 of bisection then corresponds simply to doubling $d$ and possibly
1060 adding~1. Furthermore it proves to be convenient to modify
1061 our previous conventions for bisection slightly, maintaining the
1062 variables $X_0=2^lx_0$, $X_1=2^l(x_0-x_1)$, and $X_2=2^l(x_1-x_2)$.
1063 With these variables the conditions $x_0\ge0$ and $\min(x_1,x_2)<0$ are
1064 equivalent to $\max(X_1,X_1+X_2)>X_0\ge0$.
1065
1066 The following code maintains the invariant relations
1067 $0\L|x0|<\max(|x1|,|x1|+|x2|)$,
1068 $\vert|x1|\vert<2^{30}$, $\vert|x2|\vert<2^{30}$;
1069 it has been constructed in such a way that no arithmetic overflow
1070 will occur if the inputs satisfy
1071 $a<2^{30}$, $\vert a-b\vert<2^{30}$, and $\vert b-c\vert<2^{30}$.
1072
1073 @d no_crossing { ret->data.val = fraction_one + 1; return; }
1074 @d one_crossing { ret->data.val = fraction_one; return; }
1075 @d zero_crossing { ret->data.val = 0; return; }
1076
1077 @c
1078 static void mp_crossing_point (MP mp, mp_number *ret, mp_number aa, mp_number bb, mp_number cc) {
1079 (void)mp;
1080 mpinteger64 a,b,c;
1081 mpinteger64 d; /* recursive counter */
1082 mpinteger64 x, xx, x0, x1, x2; /* temporary registers for bisection */
1083 a = aa.data.val;
1084 b = bb.data.val;
1085 c = cc.data.val;
1086 if (a < 0)
1087 zero_crossing;
1088 if (c >= 0) {
1089 if (b >= 0) {
1090 if (c > 0) {
1091 no_crossing;
1092 } else if ((a == 0) && (b == 0)) {
1093 no_crossing;
1094 } else {
1095 one_crossing;
1096 }
1097 }
1098 if (a == 0)
1099 zero_crossing;
1100 } else if (a == 0) {
1101 if (b <= 0)
1102 zero_crossing;
1103 }
1104
1105 /* Use bisection to find the crossing point... */
1106 d = 1;
1107 x0 = a;
1108 x1 = a - b;
1109 x2 = b - c;
1110 do {
1111 x = (x1 + x2) / 2;
1112 if (x1 - x0 > x0) {
1113 x2 = x;
1114 x0 += x0;
1115 d += d;
1116 } else {
1117 xx = x1 + x - x0;
1118 if (xx > x0) {
1119 x2 = x;
1120 x0 += x0;
1121 d += d;
1122 } else {
1123 x0 = x0 - xx;
1124 if (x <= x0) {
1125 if (x + x2 <= x0)
1126 no_crossing;
1127 }
1128 x1 = x;
1129 d = d + d + 1;
1130 }
1131 }
1132 } while (d < fraction_one);
1133 ret->data.val = (d - fraction_one);
1134 }
1135
1136
1137 @ We conclude this set of elementary routines with some simple rounding
1138 and truncation operations.
1139
1140
1141 @ |round_unscaled| rounds a |scaled| and converts it to |int|
1142 @c
1143 integer64 mp_round_unscaled(mp_number x_orig) {
1144 integer64 x = x_orig.data.val;
1145 if (x >= 32768) {
1146 return 1+((x-32768) / 65536);
1147 } else if ( x>=-32768) {
1148 return 0;
1149 } else {
1150 return -(1+((-(x+1)-32768) / 65536));
1151 }
1152 }
1153
1154 @ |number_floor| floors a |scaled|
1155
1156 @c
1157 void mp_number_floor (mp_number *i) {
1158 i->data.val = i->data.val&-65536;
1159 }
1160
1161 @ |fraction_to_scaled| rounds a |fraction| and converts it to |scaled|
1162 @c
1163 void mp_fraction_to_round_scaled (mp_number *x_orig) {
1164 mpinteger64 x = x_orig->data.val;
1165 x_orig->type = mp_scaled_type;
1166 x_orig->data.val = (x>=2048 ? 1+((x-2048) / 4096) : ( x>=-2048 ? 0 : -(1+((-(x+1)-2048) / 4096))));
1167 }
1168
1169
1170
1171 @* Algebraic and transcendental functions.
1172 \MP\ computes all of the necessary special functions from scratch, without
1173 relying on |real| arithmetic or system subroutines for sines, cosines, etc.
1174
1175 @ To get the square root of a |scaled| number |x|, we want to calculate
1176 $s=\lfloor 2^8\!\sqrt x +{1\over2}\rfloor$. If $x>0$, this is the unique
1177 integer such that $2^{16}x-s\L s^2<2^{16}x+s$. The following subroutine
1178 determines $s$ by an iterative method that maintains the invariant
1179 relations $x=2^{46-2k}x_0\bmod 2^{30}$, $0<y=\lfloor 2^{16-2k}x_0\rfloor
1180 -s^2+s\L q=2s$, where $x_0$ is the initial value of $x$. The value of~$y$
1181 might, however, be zero at the start of the first iteration.
1182
1183 @c
1184 void mp_square_rt (MP mp, mp_number *ret, mp_number x_orig) { /* return, x: scaled */
1185 mpinteger64 x;
1186 quarterword k; /* iteration control counter */
1187 mpinteger64 y; /* register for intermediate calculations */
1188 mpinteger64 q; /* register for intermediate calculations */
1189 x = x_orig.data.val;
1190 if (x <= 0) {
1191 @<Handle square root of zero or negative argument@>;
1192 } else {
1193 k = 23;
1194 q = 2;
1195 while (x < fraction_two) { /* i.e., |while x<@t$2^{29}$@>|\unskip */
1196 k--;
1197 x = x + x + x + x;
1198 }
1199 if (x < fraction_four)
1200 y = 0;
1201 else {
1202 x = x - fraction_four;
1203 y = 1;
1204 }
1205 do {
1206 @<Decrease |k| by 1, maintaining the invariant
1207 relations between |x|, |y|, and~|q|@>;
1208 } while (k != 0);
1209 ret->data.val = (int) (halfp (q));
1210 }
1211 }
1212
1213
1214 @ @<Handle square root of zero...@>=
1215 {
1216 if (x < 0) {
1217 char msg[256];
1218 const char *hlp[] = {
1219 "Since I don't take square roots of negative numbers,",
1220 "I'm zeroing this one. Proceed, with fingers crossed.",
1221 NULL };
1222 mp_snprintf(msg, 256, "Square root of %s has been replaced by 0", mp_string_scaled (mp, x));
1223 @.Square root...replaced by 0@>;
1224 mp_error (mp, msg, hlp, true);
1225 }
1226 ret->data.val = 0;
1227 return;
1228 }
1229
1230
1231 @ @<Decrease |k| by 1, maintaining...@>=
1232 x += x;
1233 y += y;
1234 if (x >= fraction_four) { /* note that |fraction_four=@t$2^{30}$@>| */
1235 x = x - fraction_four;
1236 y++;
1237 };
1238 x += x;
1239 y = y + y - q;
1240 q += q;
1241 if (x >= fraction_four) {
1242 x = x - fraction_four;
1243 y++;
1244 };
1245 if (y > (int) q) {
1246 y -= q;
1247 q += 2;
1248 } else if (y <= 0) {
1249 q -= 2;
1250 y += q;
1251 };
1252 k--
1253
1254 @ Pythagorean addition $\psqrt{a^2+b^2}$ is implemented by an elegant
1255 iterative scheme due to Cleve Moler and Donald Morrison [{\sl IBM Journal
1256 @^Moler, Cleve Barry@>
1257 @^Morrison, Donald Ross@>
1258 of Research and Development\/ \bf27} (1983), 577--581]. It modifies |a| and~|b|
1259 in such a way that their Pythagorean sum remains invariant, while the
1260 smaller argument decreases.
1261
1262 @c
1263 void mp_pyth_add (MP mp, mp_number *ret, mp_number a_orig, mp_number b_orig) {
1264 integer64 a, b; /* a,b : scaled */
1265 mpinteger64 r; /* register used to transform |a| and |b|, fraction */
1266 boolean big; /* is the result dangerously near $2^{31}$? */
1267 a = MPOST_ABS (a_orig.data.val);
1268 b = MPOST_ABS (b_orig.data.val);
1269 if (a < b) {
1270 r = b;
1271 b = a;
1272 a = r;
1273 }; /* now |0<=b<=a| */
1274 if (b > 0) {
1275 if (a < fraction_two) {
1276 big = false;
1277 } else {
1278 a = a / 4;
1279 b = b / 4;
1280 big = true;
1281 }; /* we reduced the precision to avoid arithmetic overflow */
1282 @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>;
1283 if (big) {
1284 if (a < fraction_two) {
1285 a = a + a + a + a;
1286 } else {
1287 mp->arith_error = true;
1288 a = EL_GORDO;
1289 };
1290 }
1291 }
1292 ret->data.val = a;
1293 }
1294
1295
1296 @ The key idea here is to reflect the vector $(a,b)$ about the
1297 line through $(a,b/2)$.
1298
1299 @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>=
1300 while (1) {
1301 r = mp_make_fraction (mp, b, a);
1302 r = mp_take_fraction (mp, r, r); /* now $r\approx b^2/a^2$ */
1303 if (r == 0)
1304 break;
1305 r = mp_make_fraction (mp, r, fraction_four + r);
1306 a = a + mp_take_fraction (mp, a + a, r);
1307 b = mp_take_fraction (mp, b, r);
1308 }
1309
1310
1311 @ Here is a similar algorithm for $\psqrt{a^2-b^2}$.
1312 It converges slowly when $b$ is near $a$, but otherwise it works fine.
1313
1314 @c
1315 void mp_pyth_sub (MP mp, mp_number *ret, mp_number a_orig, mp_number b_orig) {
1316 mpinteger64 a, b; /* a,b: scaled */
1317 mpinteger64 r; /* register used to transform |a| and |b|, fraction */
1318 boolean big; /* is the result dangerously near $2^{31}$? */
1319 a = MPOST_ABS (a_orig.data.val);
1320 b = MPOST_ABS (b_orig.data.val);
1321 if (a <= b) {
1322 @<Handle erroneous |pyth_sub| and set |a:=0|@>;
1323 } else {
1324 if (a < fraction_four) {
1325 big = false;
1326 } else {
1327 a = (integer) halfp (a);
1328 b = (integer) halfp (b);
1329 big = true;
1330 }
1331 @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>;
1332 if (big)
1333 a *= 2;
1334 }
1335 ret->data.val = a;
1336 }
1337
1338
1339 @ @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>=
1340 while (1) {
1341 r = mp_make_fraction (mp, b, a);
1342 r = mp_take_fraction (mp, r, r); /* now $r\approx b^2/a^2$ */
1343 if (r == 0)
1344 break;
1345 r = mp_make_fraction (mp, r, fraction_four - r);
1346 a = a - mp_take_fraction (mp, a + a, r);
1347 b = mp_take_fraction (mp, b, r);
1348 }
1349
1350
1351 @ @<Handle erroneous |pyth_sub| and set |a:=0|@>=
1352 {
1353 if (a < b) {
1354 char msg[256];
1355 const char *hlp[] = {
1356 "Since I don't take square roots of negative numbers,",
1357 "I'm zeroing this one. Proceed, with fingers crossed.",
1358 NULL };
1359 char *astr = strdup(mp_string_scaled (mp, a));
1360 assert (astr);
1361 mp_snprintf (msg, 256, "Pythagorean subtraction %s+-+%s has been replaced by 0", astr, mp_string_scaled (mp, b));
1362 free(astr);
1363 @.Pythagorean...@>;
1364 mp_error (mp, msg, hlp, true);
1365 }
1366 a = 0;
1367 }
1368
1369
1370 @ The subroutines for logarithm and exponential involve two tables.
1371 The first is simple: |two_to_the[k]| equals $2^k$. The second involves
1372 a bit more calculation, which the author claims to have done correctly:
1373 |spec_log[k]| is $2^{27}$ times $\ln\bigl(1/(1-2^{-k})\bigr)=
1374 2^{-k}+{1\over2}2^{-2k}+{1\over3}2^{-3k}+\cdots\,$, rounded to the
1375 nearest integer.
1376
1377 @d two_to_the(A) (1<<(unsigned)(A))
1378
1379 @<Declarations@>=
1380 static const mpinteger64 spec_log[29] = { 0, /* special logarithms */
1381 93032640, 38612034, 17922280, 8662214, 4261238, 2113709,
1382 1052693, 525315, 262400, 131136, 65552, 32772, 16385,
1383 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 1
1384 };
1385
1386
1387 @ Here is the routine that calculates $2^8$ times the natural logarithm
1388 of a |scaled| quantity; it is an integer approximation to $2^{24}\ln(x/2^{16})$,
1389 when |x| is a given positive integer.
1390
1391 The method is based on exercise 1.2.2--25 in {\sl The Art of Computer
1392 Programming\/}: During the main iteration we have $1\L 2^{-30}x<1/(1-2^{1-k})$,
1393 and the logarithm of $2^{30}x$ remains to be added to an accumulator
1394 register called~$y$. Three auxiliary bits of accuracy are retained in~$y$
1395 during the calculation, and sixteen auxiliary bits to extend |y| are
1396 kept in~|z| during the initial argument reduction. (We add
1397 $100\cdot2^{16}=6553600$ to~|z| and subtract 100 from~|y| so that |z| will
1398 not become negative; also, the actual amount subtracted from~|y| is~96,
1399 not~100, because we want to add~4 for rounding before the final division by~8.)
1400
1401 @c
1402 void mp_m_log (MP mp, mp_number *ret, mp_number x_orig) { /* return, x: scaled */
1403 mpinteger64 x;
1404 mpinteger64 y, z; /* auxiliary registers */
1405 mpinteger64 k; /* iteration counter */
1406 x = x_orig.data.val;
1407 if (x <= 0) {
1408 @<Handle non-positive logarithm@>;
1409 } else {
1410 y = 1302456956 + 4 - 100; /* $14\times2^{27}\ln2\approx1302456956.421063$ */
1411 z = 27595 + 6553600; /* and $2^{16}\times .421063\approx 27595$ */
1412 while (x < fraction_four) {
1413 x = 2*x;
1414 y -= 93032639;
1415 z -= 48782;
1416 } /* $2^{27}\ln2\approx 93032639.74436163$ and $2^{16}\times.74436163\approx 48782$ */
1417 y = y + (z / unity);
1418 k = 2;
1419 while (x > fraction_four + 4) {
1420 @<Increase |k| until |x| can be multiplied by a
1421 factor of $2^{-k}$, and adjust $y$ accordingly@>;
1422 }
1423 ret->data.val = (y / 8);
1424 }
1425 }
1426
1427
1428 @ @<Increase |k| until |x| can...@>=
1429 {
1430 z = ((x - 1) / two_to_the (k)) + 1; /* $z=\lceil x/2^k\rceil$ */
1431 while (x < fraction_four + z) {
1432 z = halfp (z + 1);
1433 k++;
1434 };
1435 y += spec_log[k];
1436 x -= z;
1437 }
1438
1439
1440 @ @<Handle non-positive logarithm@>=
1441 {
1442 char msg[256];
1443 const char *hlp[] = {
1444 "Since I don't take logs of non-positive numbers,",
1445 "I'm zeroing this one. Proceed, with fingers crossed.",
1446 NULL };
1447 mp_snprintf (msg, 256, "Logarithm of %s has been replaced by 0", mp_string_scaled (mp, x));
1448 @.Logarithm...replaced by 0@>;
1449 mp_error (mp, msg, hlp, true);
1450 ret->data.val = 0;
1451 }
1452
1453
1454 @ Conversely, the exponential routine calculates $\exp(x/2^8)$,
1455 when |x| is |scaled|. The result is an integer approximation to
1456 $2^{16}\exp(x/2^{24})$, when |x| is regarded as an integer.
1457
1458 @c
1459 void mp_m_exp (MP mp, mp_number *ret, mp_number x_orig) {
1460 quarterword k; /* loop control index */
1461 mpinteger64 y, z; /* auxiliary registers */
1462 mpinteger64 x;
1463 x = x_orig.data.val;
1464 if (x > 174436200) {
1465 /* $2^{24}\ln((2^{31}-1)/2^{16})\approx 174436199.51$ */
1466 mp->arith_error = true;
1467 ret->data.val = EL_GORDO;
1468 } else if (x < -197694359) {
1469 /* $2^{24}\ln(2^{-1}/2^{16})\approx-197694359.45$ */
1470 ret->data.val = 0;
1471 } else {
1472 if (x <= 0) {
1473 z = -8 * x;
1474 y = 04000000; /* $y=2^{20}$ */
1475 } else {
1476 if (x <= 127919879) {
1477 z = 1023359037 - 8 * x;
1478 /* $2^{27}\ln((2^{31}-1)/2^{20})\approx 1023359037.125$ */
1479 } else {
1480 z = 8 * (174436200 - x); /* |z| is always nonnegative */
1481 }
1482 y = EL_GORDO;
1483 }
1484 @<Multiply |y| by $\exp(-z/2^{27})$@>;
1485 if (x <= 127919879)
1486 ret->data.val = ((y + 8) / 16);
1487 else
1488 ret->data.val = y;
1489 }
1490 }
1491
1492
1493 @ The idea here is that subtracting |spec_log[k]| from |z| corresponds
1494 to multiplying |y| by $1-2^{-k}$.
1495
1496 A subtle point (which had to be checked) was that if $x=127919879$, the
1497 value of~|y| will decrease so that |y+8| doesn't overflow. In fact,
1498 $z$ will be 5 in this case, and |y| will decrease by~64 when |k=25|
1499 and by~16 when |k=27|.
1500
1501 @<Multiply |y| by...@>=
1502 k = 1;
1503 while (z > 0) {
1504 while (z >= spec_log[k]) {
1505 z -= spec_log[k];
1506 y = y - 1 - ((y - two_to_the (k - 1)) / two_to_the (k));
1507 }
1508 k++;
1509 }
1510
1511 @ The trigonometric subroutines use an auxiliary table such that
1512 |spec_atan[k]| contains an approximation to the |angle| whose tangent
1513 is~$1/2^k$. $\arctan2^{-k}$ times $2^{20}\cdot180/\pi$
1514
1515 @<Declarations@>=
1516 static const int spec_atan[27] = { 0, 27855475, 14718068, 7471121, 3750058,
1517 1876857, 938658, 469357, 234682, 117342, 58671, 29335, 14668, 7334, 3667,
1518 1833, 917, 458, 229, 115, 57, 29, 14, 7, 4, 2, 1
1519 };
1520
1521
1522 @ Given integers |x| and |y|, not both zero, the |n_arg| function
1523 returns the |angle| whose tangent points in the direction $(x,y)$.
1524 This subroutine first determines the correct octant, then solves the
1525 problem for |0<=y<=x|, then converts the result appropriately to
1526 return an answer in the range |-one_eighty_deg<=@t$\theta$@><=one_eighty_deg|.
1527 (The answer is |+one_eighty_deg| if |y=0| and |x<0|, but an answer of
1528 |-one_eighty_deg| is possible if, for example, |y=-1| and $x=-2^{30}$.)
1529
1530 The octants are represented in a ``Gray code,'' since that turns out
1531 to be computationally simplest.
1532
1533 @d negate_x 1
1534 @d negate_y 2
1535 @d switch_x_and_y 4
1536 @d first_octant 1
1537 @d second_octant (first_octant+switch_x_and_y)
1538 @d third_octant (first_octant+switch_x_and_y+negate_x)
1539 @d fourth_octant (first_octant+negate_x)
1540 @d fifth_octant (first_octant+negate_x+negate_y)
1541 @d sixth_octant (first_octant+switch_x_and_y+negate_x+negate_y)
1542 @d seventh_octant (first_octant+switch_x_and_y+negate_y)
1543 @d eighth_octant (first_octant+negate_y)
1544
1545 @c
1546 void mp_n_arg (MP mp, mp_number *ret, mp_number x_orig, mp_number y_orig) {
1547 mpinteger64 z; /* auxiliary register */
1548 mpinteger64 t; /* temporary storage */
1549 quarterword k; /* loop counter */
1550 int octant; /* octant code */
1551 mpinteger64 x, y;
1552 x = x_orig.data.val;
1553 y = y_orig.data.val;
1554 if (x >= 0) {
1555 octant = first_octant;
1556 } else {
1557 x = -x;
1558 octant = first_octant + negate_x;
1559 }
1560 if (y < 0) {
1561 y = -y;
1562 octant = octant + negate_y;
1563 }
1564 if (x < y) {
1565 t = y;
1566 y = x;
1567 x = t;
1568 octant = octant + switch_x_and_y;
1569 }
1570 if (x == 0) {
1571 @<Handle undefined arg@>;
1572 } else {
1573 ret->type = mp_angle_type;
1574 @<Set variable |z| to the arg of $(x,y)$@>;
1575 @<Return an appropriate answer based on |z| and |octant|@>;
1576 }
1577 }
1578
1579
1580 @ @<Handle undefined arg@>=
1581 {
1582 const char *hlp[] = {
1583 "The `angle' between two identical points is undefined.",
1584 "I'm zeroing this one. Proceed, with fingers crossed.",
1585 NULL };
1586 mp_error (mp, "angle(0,0) is taken as zero", hlp, true);
1587 @.angle(0,0)...zero@>;
1588 ret->data.val = 0;
1589 }
1590
1591
1592 @ @<Return an appropriate answer...@>=
1593 switch (octant) {
1594 case first_octant:
1595 ret->data.val = z;
1596 break;
1597 case second_octant:
1598 ret->data.val = (ninety_deg - z);
1599 break;
1600 case third_octant:
1601 ret->data.val = (ninety_deg + z);
1602 break;
1603 case fourth_octant:
1604 ret->data.val = (one_eighty_deg - z);
1605 break;
1606 case fifth_octant:
1607 ret->data.val = (z - one_eighty_deg);
1608 break;
1609 case sixth_octant:
1610 ret->data.val = (-z - ninety_deg);
1611 break;
1612 case seventh_octant:
1613 ret->data.val = (z - ninety_deg);
1614 break;
1615 case eighth_octant:
1616 ret->data.val = (-z);
1617 break;
1618 } /* there are no other cases */
1619
1620
1621 @ At this point we have |x>=y>=0|, and |x>0|. The numbers are scaled up
1622 or down until $2^{28}\L x<2^{29}$, so that accurate fixed-point calculations
1623 will be made.
1624
1625 @<Set variable |z| to the arg...@>=
1626 while (x >= fraction_two) {
1627 x = halfp (x);
1628 y = halfp (y);
1629 }
1630 z = 0;
1631 if (y > 0) {
1632 while (x < fraction_one) {
1633 x += x;
1634 y += y;
1635 };
1636 @<Increase |z| to the arg of $(x,y)$@>;
1637 }
1638
1639 @ During the calculations of this section, variables |x| and~|y|
1640 represent actual coordinates $(x,2^{-k}y)$. We will maintain the
1641 condition |x>=y|, so that the tangent will be at most $2^{-k}$.
1642 If $x<2y$, the tangent is greater than $2^{-k-1}$. The transformation
1643 $(a,b)\mapsto(a+b\tan\phi,b-a\tan\phi)$ replaces $(a,b)$ by
1644 coordinates whose angle has decreased by~$\phi$; in the special case
1645 $a=x$, $b=2^{-k}y$, and $\tan\phi=2^{-k-1}$, this operation reduces
1646 to the particularly simple iteration shown here. [Cf.~John E. Meggitt,
1647 @^Meggitt, John E.@>
1648 {\sl IBM Journal of Research and Development\/ \bf6} (1962), 210--226.]
1649
1650 The initial value of |x| will be multiplied by at most
1651 $(1+{1\over2})(1+{1\over8})(1+{1\over32})\cdots\approx 1.7584$; hence
1652 there is no chance of integer overflow.
1653
1654 @<Increase |z|...@>=
1655 k = 0;
1656 do {
1657 y += y;
1658 k++;
1659 if (y > x) {
1660 z = z + spec_atan[k];
1661 t = x;
1662 x = x + (y / two_to_the (k + k));
1663 y = y - t;
1664 };
1665 } while (k != 15);
1666 do {
1667 y += y;
1668 k++;
1669 if (y > x) {
1670 z = z + spec_atan[k];
1671 y = y - x;
1672 };
1673 } while (k != 26)
1674
1675 @ Conversely, the |n_sin_cos| routine takes an |angle| and produces the sine
1676 and cosine of that angle. The results of this routine are
1677 stored in global integer variables |n_sin| and |n_cos|.
1678
1679 @ Given an integer |z| that is $2^{20}$ times an angle $\theta$ in degrees,
1680 the purpose of |n_sin_cos(z)| is to set
1681 |x=@t$r\cos\theta$@>| and |y=@t$r\sin\theta$@>| (approximately),
1682 for some rather large number~|r|. The maximum of |x| and |y|
1683 will be between $2^{28}$ and $2^{30}$, so that there will be hardly
1684 any loss of accuracy. Then |x| and~|y| are divided by~|r|.
1685
1686 @d forty_five_deg 0264000000 /* $45\cdot2^{20}$, represents $45^\circ$ */
1687 @d ninety_deg 0550000000 /* $90\cdot2^{20}$, represents $90^\circ$ */
1688 @d one_eighty_deg 01320000000 /* $180\cdot2^{20}$, represents $180^\circ$ */
1689 @d three_sixty_deg 02640000000 /* $360\cdot2^{20}$, represents $360^\circ$ */
1690
1691 @d odd(A) (MPOST_ABS(A)%2==1)
1692
1693 @ Compute a multiple of the sine and cosine
1694
1695 @c
1696 void mp_n_sin_cos (MP mp, mp_number z_orig, mp_number *n_cos, mp_number *n_sin) {
1697 quarterword k; /* loop control variable */
1698 mpinteger64 q; /* specifies the quadrant */
1699 mpinteger64 x, y, t; /* temporary registers */
1700 mpinteger64 z; /* scaled */
1701 mp_number x_n, y_n, ret;
1702 new_number (ret);
1703 new_number (x_n);
1704 new_number (y_n);
1705 z = z_orig.data.val;
1706 while (z < 0)
1707 z = z + three_sixty_deg;
1708 z = z % three_sixty_deg; /* now |0<=z<three_sixty_deg| */
1709 q = z / forty_five_deg;
1710 z = z % forty_five_deg;
1711 x = fraction_one;
1712 y = x;
1713 if (!odd (q))
1714 z = forty_five_deg - z;
1715 @<Subtract angle |z| from |(x,y)|@>;
1716 @<Convert |(x,y)| to the octant determined by~|q|@>;
1717 x_n.data.val = x;
1718 y_n.data.val = y;
1719 mp_pyth_add (mp, &ret, x_n, y_n);
1720 n_cos->data.val = mp_make_fraction (mp, x, ret.data.val);
1721 n_sin->data.val = mp_make_fraction (mp, y, ret.data.val);
1722 free_number(ret);
1723 free_number(x_n);
1724 free_number(y_n);
1725 }
1726
1727
1728 @ In this case the octants are numbered sequentially.
1729
1730 @<Convert |(x,...@>=
1731 switch (q) {
1732 case 0:
1733 break;
1734 case 1:
1735 t = x;
1736 x = y;
1737 y = t;
1738 break;
1739 case 2:
1740 t = x;
1741 x = -y;
1742 y = t;
1743 break;
1744 case 3:
1745 x = -x;
1746 break;
1747 case 4:
1748 x = -x;
1749 y = -y;
1750 break;
1751 case 5:
1752 t = x;
1753 x = -y;
1754 y = -t;
1755 break;
1756 case 6:
1757 t = x;
1758 x = y;
1759 y = -t;
1760 break;
1761 case 7:
1762 y = -y;
1763 break;
1764 } /* there are no other cases */
1765
1766
1767 @ The main iteration of |n_sin_cos| is similar to that of |n_arg| but
1768 applied in reverse. The values of |spec_atan[k]| decrease slowly enough
1769 that this loop is guaranteed to terminate before the (nonexistent) value
1770 |spec_atan[27]| would be required.
1771
1772 @<Subtract angle |z|...@>=
1773 k = 1;
1774 while (z > 0) {
1775 if (z >= spec_atan[k]) {
1776 z = z - spec_atan[k];
1777 t = x;
1778 x = t + y / two_to_the (k);
1779 y = y - t / two_to_the (k);
1780 }
1781 k++;
1782 }
1783 if (y < 0)
1784 y = 0 /* this precaution may never be needed */
1785
1786
1787 @ To initialize the |randoms| table, we call the following routine.
1788
1789 @c
1790 void mp_init_randoms (MP mp, int seed) {
1791 int j, jj, k; /* more or less random integers */
1792 int i; /* index into |randoms| */
1793 j = abs (seed);
1794 while (j >= fraction_one) {
1795 j = j/2;
1796 }
1797 k = 1;
1798 for (i = 0; i <= 54; i++) {
1799 jj = k;
1800 k = j - k;
1801 j = jj;
1802 if (k<0)
1803 k += fraction_one;
1804 mp->randoms[(i * 21) % 55].data.val = j;
1805 }
1806 mp_new_randoms (mp);
1807 mp_new_randoms (mp);
1808 mp_new_randoms (mp); /* ``warm up'' the array */
1809 }
1810
1811
1812 @ @c
1813 void mp_print_number (MP mp, mp_number n) {
1814 mp_print_scaled (mp, n.data.val);
1815 }
1816
1817
1818 @ @c
1819 char * mp_number_tostring (MP mp, mp_number n) {
1820 return mp_string_scaled(mp, n.data.val);
1821 }
1822
1823 @ @c
1824 void mp_number_modulo (mp_number *a, mp_number b) {
1825 a->data.val = a->data.val % b.data.val;
1826 }
1827
1828
1829
1830
1831
1832 @ To consume a random fraction, the program below will say `|next_random|'.
1833
1834 @c
1835 static void mp_next_random (MP mp, mp_number *ret) {
1836 if ( mp->j_random==0 )
1837 mp_new_randoms(mp);
1838 else
1839 mp->j_random = mp->j_random-1;
1840 mp_number_clone (ret, mp->randoms[mp->j_random]);
1841 }
1842
1843
1844 @ To produce a uniform random number in the range |0<=u<x| or |0>=u>x|
1845 or |0=u=x|, given a |scaled| value~|x|, we proceed as shown here.
1846
1847 Note that the call of |take_fraction| will produce the values 0 and~|x|
1848 with about half the probability that it will produce any other particular
1849 values between 0 and~|x|, because it rounds its answers.
1850
1851 @c
1852 static void mp_m_unif_rand (MP mp, mp_number *ret, mp_number x_orig) {
1853 mp_number y; /* trial value */
1854 mp_number x, abs_x;
1855 mp_number u;
1856 new_fraction (y);
1857 new_number (x);
1858 new_number (abs_x);
1859 new_number (u);
1860 mp_number_clone (&x, x_orig);
1861 mp_number_clone (&abs_x, x);
1862 mp_number_abs (&abs_x);
1863 mp_next_random(mp, &u);
1864 /*|take_fraction (y, abs_x, u);|*/
1865 mp_number_take_fraction (mp,&y, abs_x,u);
1866 free_number (u);
1867 if (mp_number_equal(y, abs_x)) {
1868 /*|set_number_to_zero(*ret);|*/
1869 mp_number_clone (ret, ((math_data *)mp->math)->zero_t);
1870 } else if (mp_number_greater(x, ((math_data *)mp->math)->zero_t)) {
1871 mp_number_clone (ret, y);
1872 } else {
1873 mp_number_clone (ret, y);
1874 mp_number_negate (ret);
1875 }
1876 free_number (abs_x);
1877 free_number (x);
1878 free_number (y);
1879 }
1880
1881
1882
1883
1884 @ Finally, a normal deviate with mean zero and unit standard deviation
1885 can readily be obtained with the ratio method (Algorithm 3.4.1R in
1886 {\sl The Art of Computer Programming\/}).
1887
1888 @c
1889 static void mp_m_norm_rand (MP mp, mp_number *ret) {
1890 mp_number ab_vs_cd;
1891 mp_number abs_x;
1892 mp_number u;
1893 mp_number r;
1894 mp_number la, xa;
1895 new_number (ab_vs_cd);
1896 new_number (la);
1897 new_number (xa);
1898 new_number (abs_x);
1899 new_number (u);
1900 new_number (r);
1901 do {
1902 do {
1903 mp_number v;
1904 new_number (v);
1905 mp_next_random(mp, &v);
1906 mp_number_substract (&v, ((math_data *)mp->math)->fraction_half_t);
1907 mp_number_take_fraction (mp,&xa, ((math_data *)mp->math)->sqrt_8_e_k, v);
1908 free_number (v);
1909 mp_next_random(mp, &u);
1910 mp_number_clone (&abs_x, xa);
1911 mp_number_abs (&abs_x);
1912 } while (!mp_number_less(abs_x, u));
1913 mp_number_make_fraction (mp, &r, xa, u);
1914 mp_number_clone (&xa, r);
1915 mp_m_log (mp,&la, u);
1916 mp_set_number_from_substraction(&la, ((math_data *)mp->math)->twelve_ln_2_k, la);
1917 mp_ab_vs_cd (mp,&ab_vs_cd, ((math_data *)mp->math)->one_k, la, xa, xa);
1918 } while (mp_number_less(ab_vs_cd,((math_data *)mp->math)->zero_t));
1919 mp_number_clone (ret, xa);
1920 free_number (ab_vs_cd);
1921 free_number (r);
1922 free_number (abs_x);
1923 free_number (la);
1924 free_number (xa);
1925 free_number (u);
1926 }