Debian Codegraph @

terps/tads/tads3/vmbignum.cpp

raw symbols SCIP
1 #ifdef RCSID
2 static char RCSid[] =
3 "$Header$";
4 #endif
5
6 /*
7 * Copyright (c) 2000, 2002 Michael J. Roberts. All Rights Reserved.
8 *
9 * Please see the accompanying license file, LICENSE.TXT, for information
10 * on using and copying this software.
11 */
12 /*
13 Name
14 vmbignum.cpp - big number metaclass
15 Function
16
17 Notes
18
19 Modified
20 02/18/00 MJRoberts - Creation
21 */
22
23 #include <stdlib.h>
24 #include <string.h>
25 #include <assert.h>
26 #include <limits.h>
27 #include <stdarg.h>
28 #include <math.h>
29 #include <float.h>
30
31 #include "t3std.h"
32 #include "vmtype.h"
33 #include "vmmcreg.h"
34 #include "vmbignum.h"
35 #include "vmobj.h"
36 #include "vmerr.h"
37 #include "vmerrnum.h"
38 #include "vmfile.h"
39 #include "vmpool.h"
40 #include "vmstack.h"
41 #include "utf8.h"
42 #include "vmstr.h"
43 #include "vmbif.h"
44 #include "vmmeta.h"
45 #include "vmlst.h"
46 #include "vmdatasrc.h"
47
48
49 /* ------------------------------------------------------------------------ */
50 /*
51 * statics
52 */
53
54 /* metaclass registration object */
55 static CVmMetaclassBigNum metaclass_reg_obj;
56 CVmMetaclass *CVmObjBigNum::metaclass_reg_ = &metaclass_reg_obj;
57
58 /* function table */
59 int (CVmObjBigNum::
60 *CVmObjBigNum::func_table_[])(VMG_ vm_obj_id_t self,
61 vm_val_t *retval, uint *argc) =
62 {
63 &CVmObjBigNum::getp_undef,
64 &CVmObjBigNum::getp_format,
65 &CVmObjBigNum::getp_equal_rnd,
66 &CVmObjBigNum::getp_get_prec,
67 &CVmObjBigNum::getp_set_prec,
68 &CVmObjBigNum::getp_frac,
69 &CVmObjBigNum::getp_whole,
70 &CVmObjBigNum::getp_round_dec,
71 &CVmObjBigNum::getp_abs,
72 &CVmObjBigNum::getp_ceil,
73 &CVmObjBigNum::getp_floor,
74 &CVmObjBigNum::getp_get_scale,
75 &CVmObjBigNum::getp_scale,
76 &CVmObjBigNum::getp_negate,
77 &CVmObjBigNum::getp_copy_sign,
78 &CVmObjBigNum::getp_is_neg,
79 &CVmObjBigNum::getp_remainder,
80 &CVmObjBigNum::getp_sin,
81 &CVmObjBigNum::getp_cos,
82 &CVmObjBigNum::getp_tan,
83 &CVmObjBigNum::getp_deg2rad,
84 &CVmObjBigNum::getp_rad2deg,
85 &CVmObjBigNum::getp_asin,
86 &CVmObjBigNum::getp_acos,
87 &CVmObjBigNum::getp_atan,
88 &CVmObjBigNum::getp_sqrt,
89 &CVmObjBigNum::getp_ln,
90 &CVmObjBigNum::getp_exp,
91 &CVmObjBigNum::getp_log10,
92 &CVmObjBigNum::getp_pow,
93 &CVmObjBigNum::getp_sinh,
94 &CVmObjBigNum::getp_cosh,
95 &CVmObjBigNum::getp_tanh,
96 &CVmObjBigNum::getp_pi,
97 &CVmObjBigNum::getp_e,
98 &CVmObjBigNum::getp_numType
99 };
100
101
102 /* constant value 1 */
103 const unsigned char CVmObjBigNum::one_[] =
104 {
105 /* number of digits - we just need one to represent the integer 1 */
106 0x01, 0x00,
107
108 /* exponent */
109 0x01, 0x00,
110
111 /* flags */
112 0x00,
113
114 /* mantissa - just one digit is needed, but pad out the byte with zero */
115 0x10
116 };
117
118
119 #if 0
120 /*
121 * Pi to 2048 digits
122 */
123 const unsigned char CVmObjBigNum::pi_[] =
124 {
125 /* number of digits of precision */
126 0x00, 0x08,
127
128 /* base-10 exponent */
129 0x01, 0x00,
130
131 /* flags */
132 0x00,
133
134 /*
135 * the first 2048 decimal digits of pi, packed two to a byte (typed
136 * in from memory - I hope I got everything right :)
137 */
138
139 /* 1-100 */
140 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84,
141 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97,
142 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94,
143 0x45, 0x92, 0x30, 0x78, 0x16, 0x40, 0x62, 0x86, 0x20, 0x89,
144 0x98, 0x62, 0x80, 0x34, 0x82, 0x53, 0x42, 0x11, 0x70, 0x67,
145
146 /* 101-200 */
147 0x98, 0x21, 0x48, 0x08, 0x65, 0x13, 0x28, 0x23, 0x06, 0x64,
148 0x70, 0x93, 0x84, 0x46, 0x09, 0x55, 0x05, 0x82, 0x23, 0x17,
149 0x25, 0x35, 0x94, 0x08, 0x12, 0x84, 0x81, 0x11, 0x74, 0x50,
150 0x28, 0x41, 0x02, 0x70, 0x19, 0x38, 0x52, 0x11, 0x05, 0x55,
151 0x96, 0x44, 0x62, 0x29, 0x48, 0x95, 0x49, 0x30, 0x38, 0x19,
152
153 /* 201-300 */
154 0x64, 0x42, 0x88, 0x10, 0x97, 0x56, 0x65, 0x93, 0x34, 0x46,
155 0x12, 0x84, 0x75, 0x64, 0x82, 0x33, 0x78, 0x67, 0x83, 0x16,
156 0x52, 0x71, 0x20, 0x19, 0x09, 0x14, 0x56, 0x48, 0x56, 0x69,
157 0x23, 0x46, 0x03, 0x48, 0x61, 0x04, 0x54, 0x32, 0x66, 0x48,
158 0x21, 0x33, 0x93, 0x60, 0x72, 0x60, 0x24, 0x91, 0x41, 0x27,
159
160 /* 301-400 */
161 0x37, 0x24, 0x58, 0x70, 0x06, 0x60, 0x63, 0x15, 0x58, 0x81,
162 0x74, 0x88, 0x15, 0x20, 0x92, 0x09, 0x62, 0x82, 0x92, 0x54,
163 0x09, 0x17, 0x15, 0x36, 0x43, 0x67, 0x89, 0x25, 0x90, 0x36,
164 0x00, 0x11, 0x33, 0x05, 0x30, 0x54, 0x88, 0x20, 0x46, 0x65,
165 0x21, 0x38, 0x41, 0x46, 0x95, 0x19, 0x41, 0x51, 0x16, 0x09,
166
167 /* 401-500 */
168 0x43, 0x30, 0x57, 0x27, 0x03, 0x65, 0x75, 0x95, 0x91, 0x95,
169 0x30, 0x92, 0x18, 0x61, 0x17, 0x38, 0x19, 0x32, 0x61, 0x17,
170 0x93, 0x10, 0x51, 0x18, 0x54, 0x80, 0x74, 0x46, 0x23, 0x79,
171 0x96, 0x27, 0x49, 0x56, 0x73, 0x51, 0x88, 0x57, 0x52, 0x72,
172 0x48, 0x91, 0x22, 0x79, 0x38, 0x18, 0x30, 0x11, 0x94, 0x91,
173
174 /* 501-600 */
175 0x29, 0x83, 0x36, 0x73, 0x36, 0x24, 0x40, 0x65, 0x66, 0x43,
176 0x08, 0x60, 0x21, 0x39, 0x49, 0x46, 0x39, 0x52, 0x24, 0x73,
177 0x71, 0x90, 0x70, 0x21, 0x79, 0x86, 0x09, 0x43, 0x70, 0x27,
178 0x70, 0x53, 0x92, 0x17, 0x17, 0x62, 0x93, 0x17, 0x67, 0x52,
179 0x38, 0x46, 0x74, 0x81, 0x84, 0x67, 0x66, 0x94, 0x05, 0x13,
180
181 /* 601-700 */
182 0x20, 0x00, 0x56, 0x81, 0x27, 0x14, 0x52, 0x63, 0x56, 0x08,
183 0x27, 0x78, 0x57, 0x71, 0x34, 0x27, 0x57, 0x78, 0x96, 0x09,
184 0x17, 0x36, 0x37, 0x17, 0x87, 0x21, 0x46, 0x84, 0x40, 0x90,
185 0x12, 0x24, 0x95, 0x34, 0x30, 0x14, 0x65, 0x49, 0x58, 0x53,
186 0x71, 0x05, 0x07, 0x92, 0x27, 0x96, 0x89, 0x25, 0x89, 0x23,
187
188 /* 701-800 */
189 0x54, 0x20, 0x19, 0x95, 0x61, 0x12, 0x12, 0x90, 0x21, 0x96,
190 0x08, 0x64, 0x03, 0x44, 0x18, 0x15, 0x98, 0x13, 0x62, 0x97,
191 0x74, 0x77, 0x13, 0x09, 0x96, 0x05, 0x18, 0x70, 0x72, 0x11,
192 0x34, 0x99, 0x99, 0x99, 0x83, 0x72, 0x97, 0x80, 0x49, 0x95,
193 0x10, 0x59, 0x73, 0x17, 0x32, 0x81, 0x60, 0x96, 0x31, 0x85,
194
195 /* 801-900 */
196 0x95, 0x02, 0x44, 0x59, 0x45, 0x53, 0x46, 0x90, 0x83, 0x02,
197 0x64, 0x25, 0x22, 0x30, 0x82, 0x53, 0x34, 0x46, 0x85, 0x03,
198 0x52, 0x61, 0x93, 0x11, 0x88, 0x17, 0x10, 0x10, 0x00, 0x31,
199 0x37, 0x83, 0x87, 0x52, 0x88, 0x65, 0x87, 0x53, 0x32, 0x08,
200 0x38, 0x14, 0x20, 0x61, 0x71, 0x77, 0x66, 0x91, 0x47, 0x30,
201
202 /* 901-1000 */
203 0x35, 0x98, 0x25, 0x34, 0x90, 0x42, 0x87, 0x55, 0x46, 0x87,
204 0x31, 0x15, 0x95, 0x62, 0x86, 0x38, 0x82, 0x35, 0x37, 0x87,
205 0x59, 0x37, 0x51, 0x95, 0x77, 0x81, 0x85, 0x77, 0x80, 0x53,
206 0x21, 0x71, 0x22, 0x68, 0x06, 0x61, 0x30, 0x01, 0x92, 0x78,
207 0x76, 0x61, 0x11, 0x95, 0x90, 0x92, 0x16, 0x42, 0x01, 0x98,
208
209 /* 1001-1100 */
210 0x93, 0x80, 0x95, 0x25, 0x72, 0x01, 0x06, 0x54, 0x85, 0x86,
211 0x32, 0x78, 0x86, 0x59, 0x36, 0x15, 0x33, 0x81, 0x82, 0x79,
212 0x68, 0x23, 0x03, 0x01, 0x95, 0x20, 0x35, 0x30, 0x18, 0x52,
213 0x96, 0x89, 0x95, 0x77, 0x36, 0x22, 0x59, 0x94, 0x13, 0x89,
214 0x12, 0x49, 0x72, 0x17, 0x75, 0x28, 0x34, 0x79, 0x13, 0x15,
215
216 /* 1101-1200 */
217 0x15, 0x57, 0x48, 0x57, 0x24, 0x24, 0x54, 0x15, 0x06, 0x95,
218 0x95, 0x08, 0x29, 0x53, 0x31, 0x16, 0x86, 0x17, 0x27, 0x85,
219 0x58, 0x89, 0x07, 0x50, 0x98, 0x38, 0x17, 0x54, 0x63, 0x74,
220 0x64, 0x93, 0x93, 0x19, 0x25, 0x50, 0x60, 0x40, 0x09, 0x27,
221 0x70, 0x16, 0x71, 0x13, 0x90, 0x09, 0x84, 0x88, 0x24, 0x01,
222
223 /* 1201-1300 */
224 0x28, 0x58, 0x36, 0x16, 0x03, 0x56, 0x37, 0x07, 0x66, 0x01,
225 0x04, 0x71, 0x01, 0x81, 0x94, 0x29, 0x55, 0x59, 0x61, 0x98,
226 0x94, 0x67, 0x67, 0x83, 0x74, 0x49, 0x44, 0x82, 0x55, 0x37,
227 0x97, 0x74, 0x72, 0x68, 0x47, 0x10, 0x40, 0x47, 0x53, 0x46,
228 0x46, 0x20, 0x80, 0x46, 0x68, 0x42, 0x59, 0x06, 0x94, 0x91,
229
230 /* 1301-1400 */
231 0x29, 0x33, 0x13, 0x67, 0x70, 0x28, 0x98, 0x91, 0x52, 0x10,
232 0x47, 0x52, 0x16, 0x20, 0x56, 0x96, 0x60, 0x24, 0x05, 0x80,
233 0x38, 0x15, 0x01, 0x93, 0x51, 0x12, 0x53, 0x38, 0x24, 0x30,
234 0x03, 0x55, 0x87, 0x64, 0x02, 0x47, 0x49, 0x64, 0x73, 0x26,
235 0x39, 0x14, 0x19, 0x92, 0x72, 0x60, 0x42, 0x69, 0x92, 0x27,
236
237 /* 1401-1500 */
238 0x96, 0x78, 0x23, 0x54, 0x78, 0x16, 0x36, 0x00, 0x93, 0x41,
239 0x72, 0x16, 0x41, 0x21, 0x99, 0x24, 0x58, 0x63, 0x15, 0x03,
240 0x02, 0x86, 0x18, 0x29, 0x74, 0x55, 0x57, 0x06, 0x74, 0x98,
241 0x38, 0x50, 0x54, 0x94, 0x58, 0x85, 0x86, 0x92, 0x69, 0x95,
242 0x69, 0x09, 0x27, 0x21, 0x07, 0x97, 0x50, 0x93, 0x02, 0x95,
243
244 /* 1501-1600 */
245 0x53, 0x21, 0x16, 0x53, 0x44, 0x98, 0x72, 0x02, 0x75, 0x59,
246 0x60, 0x23, 0x64, 0x80, 0x66, 0x54, 0x99, 0x11, 0x98, 0x81,
247 0x83, 0x47, 0x97, 0x75, 0x35, 0x66, 0x36, 0x98, 0x07, 0x42,
248 0x65, 0x42, 0x52, 0x78, 0x62, 0x55, 0x18, 0x18, 0x41, 0x75,
249 0x74, 0x67, 0x28, 0x90, 0x97, 0x77, 0x72, 0x79, 0x38, 0x00,
250
251 /* 1601-1700 */
252 0x08, 0x16, 0x47, 0x06, 0x00, 0x16, 0x14, 0x52, 0x49, 0x19,
253 0x21, 0x73, 0x21, 0x72, 0x14, 0x77, 0x23, 0x50, 0x14, 0x14,
254 0x41, 0x97, 0x35, 0x68, 0x54, 0x81, 0x61, 0x36, 0x11, 0x57,
255 0x35, 0x25, 0x52, 0x13, 0x34, 0x75, 0x74, 0x18, 0x49, 0x46,
256 0x84, 0x38, 0x52, 0x33, 0x23, 0x90, 0x73, 0x94, 0x14, 0x33,
257
258 /* 1701-1800 */
259 0x34, 0x54, 0x77, 0x62, 0x41, 0x68, 0x62, 0x51, 0x89, 0x83,
260 0x56, 0x94, 0x85, 0x56, 0x20, 0x99, 0x21, 0x92, 0x22, 0x18,
261 0x42, 0x72, 0x55, 0x02, 0x54, 0x25, 0x68, 0x87, 0x67, 0x17,
262 0x90, 0x49, 0x46, 0x01, 0x65, 0x34, 0x66, 0x80, 0x49, 0x88,
263 0x62, 0x72, 0x32, 0x79, 0x17, 0x86, 0x08, 0x57, 0x84, 0x38,
264
265 /* 1801-1900 */
266 0x38, 0x27, 0x96, 0x79, 0x76, 0x68, 0x14, 0x54, 0x10, 0x09,
267 0x53, 0x88, 0x37, 0x86, 0x36, 0x09, 0x50, 0x68, 0x00, 0x64,
268 0x22, 0x51, 0x25, 0x20, 0x51, 0x17, 0x39, 0x29, 0x84, 0x89,
269 0x60, 0x84, 0x12, 0x84, 0x88, 0x62, 0x69, 0x45, 0x60, 0x42,
270 0x41, 0x96, 0x52, 0x85, 0x02, 0x22, 0x10, 0x66, 0x11, 0x86,
271
272 /* 1901-2000 */
273 0x30, 0x67, 0x44, 0x27, 0x86, 0x22, 0x03, 0x91, 0x94, 0x94,
274 0x50, 0x47, 0x12, 0x37, 0x13, 0x78, 0x69, 0x60, 0x95, 0x63,
275 0x64, 0x37, 0x19, 0x17, 0x28, 0x74, 0x67, 0x76, 0x46, 0x57,
276 0x57, 0x39, 0x62, 0x41, 0x38, 0x90, 0x86, 0x58, 0x32, 0x64,
277 0x59, 0x95, 0x81, 0x33, 0x90, 0x47, 0x80, 0x27, 0x59, 0x00,
278
279 /* 2001-2048 */
280 0x99, 0x46, 0x57, 0x64, 0x07, 0x89, 0x51, 0x26, 0x94, 0x68,
281 0x39, 0x83, 0x52, 0x59, 0x57, 0x09, 0x82, 0x58, 0x22, 0x62,
282 0x05, 0x22, 0x48, 0x94
283 };
284 #endif
285
286 /* ------------------------------------------------------------------------ */
287 /*
288 * The BigNumber internal cache. This is meant to be private to the
289 * vmbignum module, but since the module is actually split between
290 * vmbignum.cpp and vmbignumlib.cpp, we need to use a C++ global. We use
291 * the S_ naming prefix to emphasize that it's conceptually a "static"
292 * variable, private to this two-file module.
293 */
294 extern CVmBigNumCache *S_bignum_cache;
295
296 /* ------------------------------------------------------------------------ */
297 /*
298 * Static creation methods. These routines allocate an object ID and
299 * create a new object.
300 */
301
302
303 /* create dynamically using stack arguments */
304 vm_obj_id_t CVmObjBigNum::create_from_stack(VMG_ const uchar **pc_ptr,
305 uint argc)
306 {
307 vm_obj_id_t id;
308 vm_val_t *val;
309 size_t digits;
310 const char *strval = 0;
311 const CVmObjBigNum *objval = 0;
312
313 /* check arguments */
314 if (argc < 1 || argc > 2)
315 err_throw(VMERR_WRONG_NUM_OF_ARGS);
316
317 /*
318 * check the first argument, which gives the source value - this can be
319 * an integer, a string, or another BigNumber value
320 */
321 val = G_stk->get(0);
322 if (val->typ == VM_INT)
323 {
324 /* we'll use the integer value */
325 }
326 else if (val->typ == VM_OBJ && is_bignum_obj(vmg_ val->val.obj))
327 {
328 /* we'll use the BigNumber value as the source */
329 objval = (CVmObjBigNum *)vm_objp(vmg_ val->val.obj);
330 }
331 else if ((strval = val->get_as_string(vmg0_)) != 0)
332 {
333 /* we'll parse the string value */
334 }
335 else
336 {
337 /* it's not a source type we accept */
338 err_throw(VMERR_NUM_VAL_REQD);
339 }
340
341 /*
342 * get the precision value, if provided; if not, infer it from the
343 * source value
344 */
345 if (argc > 1)
346 {
347 /* make sure it's an integer */
348 if (G_stk->get(1)->typ != VM_INT)
349 err_throw(VMERR_INT_VAL_REQD);
350
351 /* retrieve the value */
352 digits = (size_t)G_stk->get(1)->val.intval;
353 }
354 else if (strval != 0)
355 {
356 /* parse the string to infer the precision */
357 digits = precision_from_string(
358 strval + VMB_LEN, vmb_get_len(strval), 10);
359 }
360 else if (objval != 0)
361 {
362 /* use the same precision as the source BigNumber value */
363 digits = get_prec(objval->get_ext());
364 }
365 else
366 {
367 /* use a default precision */
368 digits = 32;
369 }
370
371 /* create the value */
372 if (strval != 0)
373 {
374 /* create the value from the string */
375 id = vm_new_id(vmg_ FALSE, FALSE, FALSE);
376 new (vmg_ id) CVmObjBigNum(vmg_ strval + VMB_LEN,
377 vmb_get_len(strval), digits);
378 }
379 else if (objval != 0)
380 {
381 vm_val_t new_val;
382
383 /* create the value based on the BigNumber value */
384 round_val(vmg_ &new_val, objval->get_ext(), digits, TRUE);
385
386 /* return the new object ID */
387 id = new_val.val.obj;
388 }
389 else
390 {
391 /* create the value based on the integer value */
392 id = vm_new_id(vmg_ FALSE, FALSE, FALSE);
393 new (vmg_ id) CVmObjBigNum(vmg_ (long)val->val.intval, digits);
394 }
395
396 /* discard arguments */
397 G_stk->discard(argc);
398
399 /* return the new object */
400 return id;
401 }
402
403 /* create with a given precision */
404 vm_obj_id_t CVmObjBigNum::create(VMG_ int in_root_set, size_t digits)
405 {
406 vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE);
407 new (vmg_ id) CVmObjBigNum(vmg_ digits);
408 return id;
409 }
410
411 /* create from an integer value */
412 vm_obj_id_t CVmObjBigNum::create(VMG_ int in_root_set,
413 long val, size_t digits)
414 {
415 vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE);
416 new (vmg_ id) CVmObjBigNum(vmg_ val, digits);
417 return id;
418 }
419
420 /* create from an unsigned integer value */
421 vm_obj_id_t CVmObjBigNum::createu(VMG_ int in_root_set,
422 ulong val, size_t digits)
423 {
424 vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE);
425 new (vmg_ id) CVmObjBigNum(vmg_ digits);
426 set_uint_val(((CVmObjBigNum *)vm_objp(vmg_ id))->get_ext(), val);
427 return id;
428 }
429
430 /* create from a 64-bit unsigned int expressed as two 32-bit segments */
431 vm_obj_id_t CVmObjBigNum::create_int64(VMG_ int in_root_set,
432 uint32_t hi, uint32_t lo)
433 {
434 /*
435 * Store into our portable 8-byte format: the portable format is
436 * little-endian, so simply store the low part in the first four bytes,
437 * and the high part in the second four bytes.
438 */
439 char buf[8];
440 oswp4(buf, lo);
441 oswp4(buf+4, hi);
442
443 /*
444 * Now create the value from the buffer. (This could be implemented a
445 * little more efficiently by working directly from the integers, but
446 * this is certainly not on any critical paths, and the create_rp8 code
447 * already exists and works.)
448 */
449 return create_rp8(vmg_ in_root_set, buf);
450 }
451
452 /* create from a 64-bit unsigned int expressed in portable 8-byte format */
453 vm_obj_id_t CVmObjBigNum::create_rp8(VMG_ int in_root_set,
454 const char *buf)
455 {
456 /*
457 * create the BigNumber object big enough to hold a 64-bit integer
458 * value, which can have up to 20 digits
459 */
460 vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE);
461 new (vmg_ id) CVmObjBigNum(vmg_ 20);
462 CVmObjBigNum *n = (CVmObjBigNum *)vm_objp(vmg_ id);
463
464 /* set the value */
465 n->set_rp8((const uchar *)buf);
466
467 /* the source value is unsigned, so it's always non-negative */
468 set_neg(n->get_ext(), FALSE);
469
470 /* return the object */
471 return id;
472 }
473
474 /* create from a 64-bit signed int */
475 vm_obj_id_t CVmObjBigNum::create_rp8s(VMG_ int in_root_set,
476 const char *buf)
477 {
478 /*
479 * create the BigNumber object big enough to hold a 64-bit integer
480 * value, which can have up to 20 digits
481 */
482 vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE);
483 new (vmg_ id) CVmObjBigNum(vmg_ 20);
484 CVmObjBigNum *n = (CVmObjBigNum *)vm_objp(vmg_ id);
485
486 /* make a private copy of the source value */
487 uchar p[8];
488 memcpy(p, buf, 8);
489
490 /*
491 * If the value is negative, as indicated by the sign bit on the most
492 * significant byte, get the absolute value by computing the two's
493 * complement. This makes the arithmetic easy because we can do the
494 * bit twiddling with unsigned values, and just set the BigNum sign bit
495 * when we're done with all of that.
496 *
497 * Note that this 2's complement arithmetic is truly portable - it
498 * doesn't matter whether the local machine's native int type is
499 * big-endian or little-endian or some bizarre interleaved-endian, or
500 * if it uses 2's complement notation or some other wacky bygone scheme
501 * (1's complement, sign bit only, etc). The reason this code is
502 * portable regardless of the local notation is that we're not
503 * operating on local int types: we're operating on a buffer that's in
504 * a universal notation that we define as 64-bit 2's complement
505 * little-endian. We're doing our work at the byte level, so as long
506 * as the local machine has 8+-bit bytes (which is a requirement for
507 * the platform to have a C compiler), this code is portable.
508 */
509 int neg = (p[7] & 0x80) != 0;
510 if (neg)
511 twos_complement_p8(p);
512
513 /* set the 64-bit int value */
514 n->set_rp8(p);
515
516 /* set the sign bit */
517 set_neg(n->get_ext(), neg);
518
519 /* return the object */
520 return id;
521 }
522
523 /* set the value from an unsigned 64-bit little-endian buffer */
524 void CVmObjBigNum::set_rp8(const uchar *p)
525 {
526 /*
527 * set up temporary registers with enough precision for 64-bit ints (we
528 * need at most 20 digits for these values)
529 */
530 char tmp1[5 + 20] = { 20, 0, 0, 0, 0 };
531 char tmp2[5 + 20] = { 20, 0, 0, 0, 0 };
532
533 /*
534 * shift in bits 24 at a time - this makes the math fit in 32-bit ints
535 * so that we don't have to worry about int overflows
536 */
537 set_uint_val(get_ext(),
538 (((ulong)p[7]) << 16) | (((ulong)p[6]) << 8) | p[5]);
539
540 mul_by_long(get_ext(), 0x01000000);
541 set_uint_val(tmp1, (((ulong)p[4]) << 16) | (((ulong)p[3]) << 8) | p[2]);
542 compute_sum_into(tmp2, get_ext(), tmp1);
543
544 mul_by_long(tmp2, 0x10000);
545 set_uint_val(tmp1, (((ulong)p[1]) << 8) | p[0]);
546 compute_sum_into(get_ext(), tmp2, tmp1);
547 }
548
549 /* create from a string value */
550 vm_obj_id_t CVmObjBigNum::create(VMG_ int in_root_set,
551 const char *str, size_t len, size_t digits)
552 {
553 vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE);
554 new (vmg_ id) CVmObjBigNum(vmg_ str, len, digits);
555 return id;
556 }
557
558 /* create from a string value, inferring the required precision */
559 vm_obj_id_t CVmObjBigNum::create(VMG_ int in_root_set,
560 const char *str, size_t len)
561 {
562 int digits = precision_from_string(str, len, 10);
563 vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE);
564 new (vmg_ id) CVmObjBigNum(vmg_ str, len, digits);
565 return id;
566 }
567
568 /* create from a string value in a given radix */
569 vm_obj_id_t CVmObjBigNum::create_radix(
570 VMG_ int in_root_set, const char *str, size_t len, int radix)
571 {
572 int digits = precision_from_string(str, len, radix);
573 vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE);
574 if (radix == 10)
575 new (vmg_ id) CVmObjBigNum(vmg_ str, len, digits);
576 else
577 {
578 new (vmg_ id) CVmObjBigNum(vmg_ digits);
579 ((CVmObjBigNum *)vm_objp(vmg_ id))->set_str_val(str, len, radix);
580 }
581 return id;
582 }
583
584 /* create from a double value, with enough precision for a native double */
585 vm_obj_id_t CVmObjBigNum::create(VMG_ int in_root_set, double val)
586 {
587 int digits = DBL_DIG + 2;
588 vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE);
589 new (vmg_ id) CVmObjBigNum(vmg_ val, digits);
590 return id;
591 }
592
593 /* create from a double value, with specified precision */
594 vm_obj_id_t CVmObjBigNum::create(VMG_ int in_root_set, double val,
595 size_t digits)
596 {
597 vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE);
598 new (vmg_ id) CVmObjBigNum(vmg_ val, digits);
599 return id;
600 }
601
602 /*
603 * Create from a BER-encoded compressed integer value
604 */
605 vm_obj_id_t CVmObjBigNum::create_from_ber(VMG_ int in_root_set,
606 const char *buf, size_t len)
607 {
608 /*
609 * Create the object. The source value has 7 bits of precision per
610 * byte. We need log(2)/log(10) digits of precision per bit of
611 * precision, which is about 0.30103 digits per bit.
612 */
613 int prec = (int)(len*7*0.30103 + 0.5);
614 vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE);
615 new (vmg_ id) CVmObjBigNum(vmg_ prec);
616 CVmObjBigNum *n = (CVmObjBigNum *)vm_objp(vmg_ id);
617 char *ext = n->get_ext();
618
619 /* allocate two temporary registers for intermediate sums */
620 char *t1, *t2;
621 uint hdl1, hdl2;
622 alloc_temp_regs((size_t)prec, 2, &t1, &hdl1, &t2, &hdl2);
623
624 /* zero the accumulator (start with t1) */
625 set_zero(t1);
626
627 /* set up a stack register for the base-128 digits */
628 char dig[5 + 3] = { 3, 0, 0, 0, 0 };
629
630 /* starting at the most significant byte, shift in the bits */
631 for (size_t i = 0 ; i < len ; ++i)
632 {
633 /* multiply the accumulator by 2^7 */
634 mul_by_long(t1, 128);
635
636 /* add in the next base-128 digit */
637 set_uint_val(dig, buf[i] & 0x7f);
638 compute_sum_into(t2, t1, dig);
639
640 /* swap registers so that t2 becomes the accumulator */
641 char *tt = t1; t1 = t2; t2 = tt;
642 }
643
644 /* copy the accumulator into the result */
645 copy_val(ext, t1, FALSE);
646
647 /* done with the temporary registers */
648 release_temp_regs(2, hdl1, hdl2);
649
650 /* return the new ID */
651 return id;
652 }
653
654 /*
655 * Create from a floating point value encoded in an IEEE 754-2008 binary
656 * interchange format, little-endian order. We accept bit sizes of 16, 32,
657 * 64, and 128 (half, single, double, and quad precision).
658 *
659 */
660 vm_obj_id_t CVmObjBigNum::create_from_ieee754(
661 VMG_ int in_root_set, const char *buf, int bits)
662 {
663 /*
664 * Create the object. Use the decimal equivalent precision of the IEEE
665 * 754 object. Note that we use 17 digits for doubles; the binary type
666 * stores 53 bits of mantissa == 15.95 decimal digits, but there's a
667 * pathological case at 1+epsilon, which is 1 + 2e-16, which requires
668 * 17 decimal digits to store.
669 */
670 int prec = (bits == 16 ? 4 : bits == 32 ? 8 : bits == 64 ? 17 :
671 bits == 128 ? 35 : 8);
672 vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE);
673 new (vmg_ id) CVmObjBigNum(vmg_ prec);
674 CVmObjBigNum *n = (CVmObjBigNum *)vm_objp(vmg_ id);
675
676 /* decode the IEEE 754 value */
677 n->set_ieee754_value(vmg_ buf, bits);
678
679 /* return the new object id */
680 return id;
681 }
682
683
684
685 /* ------------------------------------------------------------------------ */
686 /*
687 * Cast a value to BigNumber
688 */
689 void CVmObjBigNum::cast_to_bignum(VMG_ vm_val_t *bnval,
690 const vm_val_t *srcval)
691 {
692 const char *str;
693 if (srcval->typ == VM_INT)
694 {
695 /* create from the integer value */
696 bnval->set_obj(create(
697 vmg_ FALSE, (long)srcval->val.intval, (size_t)10));
698 }
699 else if ((str = srcval->get_as_string(vmg0_)) != 0)
700 {
701 /* get the string length and buffer pointer */
702 size_t len = vmb_get_len(str);
703 str += VMB_LEN;
704
705 /* create from the string value */
706 bnval->set_obj(create(vmg_ FALSE, str, len));
707 }
708 else if (srcval->typ == VM_OBJ && is_bignum_obj(vmg_ srcval->val.obj))
709 {
710 /* it's already a BigNumber - just return the same value */
711 bnval->set_obj(srcval->val.obj);
712 }
713 else
714 {
715 /* can't cast to BigNumber */
716 err_throw(VMERR_NO_BIGNUM_CONV);
717 }
718 }
719
720
721 /*
722 * Promote an integer value to BigNumber
723 */
724 void CVmObjBigNum::promote_int(VMG_ vm_val_t *val) const
725 {
726 val->set_obj(create(vmg_ FALSE, (long)val->val.intval, (size_t)10));
727 }
728
729
730 /* ------------------------------------------------------------------------ */
731 /*
732 * Constructors. These are called indirectly through our static
733 * creation methods.
734 */
735
736 /*
737 * Create with no extension
738 */
739 CVmObjBigNum::CVmObjBigNum()
740 {
741 /* no extension */
742 ext_ = 0;
743 }
744
745 /*
746 * Create with a given precision
747 */
748 CVmObjBigNum::CVmObjBigNum(VMG_ size_t digits)
749 {
750 /* allocate space */
751 alloc_bignum(vmg_ digits);
752 }
753
754 /*
755 * Create with a given integer value
756 */
757 CVmObjBigNum::CVmObjBigNum(VMG_ long val, size_t digits)
758 {
759 /* allocate space */
760 alloc_bignum(vmg_ digits);
761
762 /* set the value */
763 set_int_val(ext_, val);
764 }
765
766 /*
767 * Create with a given string as the source value
768 */
769 CVmObjBigNum::CVmObjBigNum(VMG_ const char *str, size_t len, size_t digits)
770 {
771 /* allocate space */
772 alloc_bignum(vmg_ digits);
773
774 /* set the value */
775 set_str_val(str, len);
776 }
777
778 /*
779 * Create from a double value
780 */
781 CVmObjBigNum::CVmObjBigNum(VMG_ double val, size_t digits)
782 {
783 /* allocate space */
784 alloc_bignum(vmg_ digits);
785
786 /* set the value */
787 set_double_val(ext_, val);
788 }
789
790 /* ------------------------------------------------------------------------ */
791 /*
792 * Delete
793 */
794 void CVmObjBigNum::notify_delete(VMG_ int in_root_set)
795 {
796 /*
797 * free our extension - do this only if it's not in the root set,
798 * because extension will be directly in the image data for a root
799 * set object
800 */
801 if (ext_ != 0 && !in_root_set)
802 G_mem->get_var_heap()->free_mem(ext_);
803 }
804
805
806 /* ------------------------------------------------------------------------ */
807 /*
808 * Allocate space for a given precision
809 */
810 void CVmObjBigNum::alloc_bignum(VMG_ size_t digits)
811 {
812 /* allocate space for the given number of elements */
813 ext_ = (char *)G_mem->get_var_heap()
814 ->alloc_mem(calc_alloc(digits), this);
815
816 /* set the precision */
817 set_prec(ext_, digits);
818
819 /* initialize the value to zero */
820 set_int_val(ext_, 0);
821
822 /* clear the flags */
823 ext_[VMBN_FLAGS] = 0;
824 }
825
826 /* ------------------------------------------------------------------------ */
827 /*
828 * Write to a 'data' mode file
829 */
830 int CVmObjBigNum::write_to_data_file(CVmDataSource *fp)
831 {
832 char buf[16];
833
834 /* write the number of digits (i.e., the precision) */
835 oswp2(buf, get_prec(ext_));
836 if (fp->write(buf, 2))
837 return 1;
838
839 /* write our entire extension */
840 if (fp->write(ext_, calc_alloc(get_prec(ext_))))
841 return 1;
842
843 /* success */
844 return 0;
845 }
846
847 /*
848 * Read from a 'data' mode file and instantiate a new BigNumber object to
849 * hold the result
850 */
851 int CVmObjBigNum::read_from_data_file(VMG_ vm_val_t *retval, CVmDataSource *fp)
852 {
853 char buf[16];
854 size_t prec;
855 CVmObjBigNum *bignum;
856
857 /* read the precision */
858 if (fp->read(buf, 2))
859 return 1;
860 prec = osrp2(buf);
861
862 /* create a BigNumber with the required precision */
863 retval->set_obj(create(vmg_ FALSE, prec));
864 bignum = (CVmObjBigNum *)vm_objp(vmg_ retval->val.obj);
865
866 /* read the bytes into the new object's extension */
867 if (fp->read(bignum->get_ext(), calc_alloc(prec)))
868 return 1;
869
870 /* success */
871 return 0;
872 }
873
874
875 /* ------------------------------------------------------------------------ */
876 /*
877 * Set my value to a string
878 */
879 void CVmObjBigNum::set_str_val(const char *str, size_t len)
880 {
881 /* parse the string into my extension */
882 parse_str_into(ext_, str, len);
883 }
884
885 /*
886 * Set my string value with a given radix. If the radix is decimal, we'll
887 * use the regular floating point parser. Otherwise we'll parse it as an
888 * integer value in the given radix.
889 */
890 void CVmObjBigNum::set_str_val(const char *str, size_t len, int radix)
891 {
892 /* parse the string into my extension using the given radix */
893 parse_str_into(ext_, str, len, radix);
894 }
895
896 /* ------------------------------------------------------------------------ */
897 /*
898 * IEEE 754-2008 binary interchange format buffer manipulation. We arrange
899 * our buffer in little-endian order to match the idiosyncratic TADS
900 * pack/unpack formats, but otherwise we use the standard IEEE formats.
901 */
902
903 /* IEEE 754-2008 buffer */
904 struct ieee754
905 {
906 ieee754(char *buf, int bits)
907 {
908 /* remember the buffer and bit size */
909 this->buf = (unsigned char *)buf;
910 this->bits = bits;
911 this->bytes = bits/8;
912
913 /* get the mantissa size (in bits) for the format size */
914 mbits = (bits == 16 ? 10 :
915 bits == 32 ? 23 :
916 bits == 64 ? 52 :
917 bits == 128 ? 112 :
918 0);
919 if (mbits == 0)
920 err_throw(VMERR_NO_DOUBLE_CONV);
921
922 /* the exponent uses the leftover bits, minus the sign bit */
923 ebits = bits - mbits - 1;
924
925 /* figure the exponent bias - it's the halfway point for the range */
926 ebias = (1 << (ebits - 1)) - 1;
927
928 /* figure the exponent range */
929 emin = 1 - ebias;
930 emax = ebias;
931 }
932
933 /*
934 * Get the number of decimal digits this type can represent. The
935 * decimal precision is fractional, since the IEEE type is binary; we
936 * round up to the next integer. There's a
937 */
938 int decimal_digits()
939 {
940 return bits == 16 ? 4 : bits == 32 ? 8 : bits == 64 ? 17 :
941 bits == 128 ? 35 : 0;
942 }
943
944 /* get the maximum number of decimal digits in the exponent */
945 int decimal_exp_digits()
946 {
947 return ebits <= 5 ? 2 : ebits <= 7 ? 3 : ebits <= 11 ? 4 : 5;
948 }
949
950 /* is the value infinity? */
951 int is_infinity() const
952 {
953 /* infinity has an exponent of emax+1 and a zero mantissa */
954 return get_exp() == emax + 1 && is_mantissa_zero();
955 }
956
957 /* set Infinity */
958 void set_infinity(int neg)
959 {
960 /*
961 * Infinity is represented with the maximum exponent plus one, and
962 * the mantissa set to all zeros. Infinities can be positive or
963 * negative, so set the sign bit.
964 */
965 memset(buf, 0, bytes);
966 set_exp(emax + 1);
967 set_sign(neg);
968 }
969
970 /* is the value zero? */
971 int is_zero() const
972 {
973 /*
974 * a zero is represented by all bits zero except possibly the sign
975 * bit, which is 0 for +0 and 1 for -0
976 */
977 int sum = 0;
978 for (int i = 0 ; i < bytes - 1 ; ++i)
979 sum += buf[i];
980
981 return sum == 0 && (buf[bytes-1] & 0x7f) == 0;
982 }
983
984 /* set Zero */
985 void set_zero(int neg)
986 {
987 /*
988 * Zero is represented with an exponent of zero and all zero bits
989 * in the mantissa. Zeros can be positive or negative, so set the
990 * sign bit.
991 */
992 memset(buf, 0, bytes);
993 set_sign(neg);
994 }
995
996 /* is this a NAN value? */
997 int is_nan() const
998 {
999 /* a NAN value has an exponent of emax+1 and a non-zero mantissa */
1000 return get_exp() == emax + 1 && !is_mantissa_zero();
1001 }
1002
1003 /* is the mantissa zero? */
1004 int is_mantissa_zero() const
1005 {
1006 /* add up the full bytes of the mantissa, plus the partial high byte */
1007 int imsb = mantissa_msb_index();
1008 int sum = buf[imsb] & mantissa_msb_mask();
1009 for (int i = 0 ; i < imsb ; sum += buf[i++]) ;
1010
1011 /* the mantissa is zero if the sum of the bytes is zero */
1012 return (sum == 0);
1013 }
1014
1015 /* get the bit mask for the partial high-order byte of the mantissa */
1016 unsigned char mantissa_msb_mask() const
1017 {
1018 if (ebits <= 7)
1019 return (0x7f >> ebits);
1020 else if (ebits <= 15)
1021 return (0xff >> (ebits - 7));
1022 else
1023 {
1024 assert(FALSE);
1025 return 0;
1026 }
1027 }
1028
1029 /* get the index of the most significant byte of the mantissa */
1030 int mantissa_msb_index() const
1031 {
1032 if (ebits <= 7)
1033 return bytes - 1;
1034 else if (ebits <= 15)
1035 return bytes - 2;
1036 else
1037 {
1038 assert(FALSE);
1039 return 0;
1040 }
1041 }
1042
1043 /* set NAN (not a number) */
1044 void set_nan()
1045 {
1046 /*
1047 * NAN (Not A Number) is represented with the maximum exponent plus
1048 * one, and a non-zero mantissa.
1049 */
1050 set_exp(emax + 1);
1051 set_mbit(0, 1);
1052 }
1053
1054 /* get the sign bit - false -> positive, true -> negative */
1055 int get_sign() const
1056 {
1057 return (buf[bytes-1] & 0x80) != 0;
1058 }
1059
1060 /* set the sign bit */
1061 void set_sign(int neg)
1062 {
1063 if (neg)
1064 buf[bytes-1] |= 0x80;
1065 else
1066 buf[bytes-1] &= 0x7f;
1067 }
1068
1069 /* get the byte index and bit mask for a mantissa bit */
1070 inline void get_mbit_ptr(int &byteidx, unsigned char &mask, int n) const
1071 {
1072 /* figure the raw bit vector index, past the sign and exponent bits */
1073 n += 1 + ebits;
1074
1075 /* get the byte index (little-endian order) */
1076 byteidx = bytes - 1 - n/8;
1077
1078 /* get the bit index within the byte, and the corresponding bit mask */
1079 n = 7 - (n % 8);
1080 mask = 1 << n;
1081 }
1082
1083 /* set the nth bit of the mantissa (0 is the high-order bit) */
1084 void set_mbit(int n, int bit)
1085 {
1086 /* get the mantissa byte index and mask */
1087 int byteidx;
1088 unsigned char mask;
1089 get_mbit_ptr(byteidx, mask, n);
1090
1091 /* set or clear the bit */
1092 if (bit)
1093 buf[byteidx] |= mask;
1094 else
1095 buf[byteidx] &= ~mask;
1096 }
1097
1098 /*
1099 * Round up - add 1 to the lowest bit. Returns true if we carried to
1100 * out of the highest order bit, false if not.
1101 *
1102 * Carrying means that we carried into the implied "1" above the first
1103 * stored bit. That bumps that bit to 0 and carries to the next bit,
1104 * so we now have an implied "10" before the first bit. The caller
1105 * must renormalize simply by incrementing the exponent. (The caller
1106 * doesn't have to worry about whether this is a normal or subnormal
1107 * number, because bumping the exponent works for both. For
1108 * subnormals, we carry into the implied "0" above the first bit, which
1109 * bumps it to 1, which puts us in the normalized range, which we
1110 * represent by bumping the exponent up one to emin.)
1111 */
1112 int round_up()
1113 {
1114 /* add to the low byte, and carry as needed to whole bytes */
1115 int imsb = mantissa_msb_index();
1116 for (int i = 0 ; i < imsb ; ++i)
1117 {
1118 if (buf[i] == 0xff)
1119 {
1120 /* this overflows the byte - zero it and carry to the next */
1121 buf[i] = 0;
1122 }
1123 else
1124 {
1125 /* no overflow - increment this byte and return "no carry" */
1126 buf[i] += 1;
1127 return FALSE;
1128 }
1129 }
1130
1131 /*
1132 * if we got this far, we've carried into the most significant
1133 * byte, which is a partial byte - we need to use the msb bit mask
1134 * for this arithmetic
1135 */
1136 unsigned char mask = mantissa_msb_mask();
1137 int b = (buf[imsb] + 1) & mask;
1138 buf[imsb] &= ~mask;
1139 buf[imsb] |= b;
1140
1141 /* if we wrapped that to zero, we carried into the implied lead bit */
1142 return (b == 0);
1143 }
1144
1145 int get_mbit(int n) const
1146 {
1147 /* get the mantissa byte index and mask */
1148 int byteidx;
1149 unsigned char mask;
1150 get_mbit_ptr(byteidx, mask, n);
1151
1152 /* return the bit value */
1153 return (buf[byteidx] & mask) != 0;
1154 }
1155
1156 /* set the exponent, adjusting for the bias */
1157 void set_exp(int e)
1158 {
1159 /* add the bias, and set the raw exponent */
1160 set_raw_exp(ebias + e);
1161 }
1162
1163 /* set the raw exponent, without the bias adjustment */
1164 void set_raw_exp(int e)
1165 {
1166 int mask;
1167 if (ebits <= 7)
1168 {
1169 /* it fits entirely in the first byte */
1170 mask = (0xff << (7 - ebits)) & 0x7f;
1171 buf[bytes-1] &= ~mask;
1172 buf[bytes-1] |= (e << (7 - ebits)) & mask;
1173 }
1174 else if (ebits <= 15)
1175 {
1176 /* it fits in the first two bytes */
1177 buf[bytes-1] &= 0x80;
1178 buf[bytes-1] |= (e >> (ebits - 7)) & 0x7f;
1179
1180 mask = (0xff << (15 - ebits)) & 0xff;
1181 buf[bytes-2] &= ~mask;
1182 buf[bytes-2] |= (e << (15 - ebits)) & mask;
1183 }
1184 else
1185 {
1186 /* we don't currently handle anything above quad precision */
1187 assert(FALSE);
1188 }
1189 }
1190
1191 /* get the exponent, adjusting for the bias */
1192 int get_exp() const { return get_raw_exp() - ebias; }
1193
1194 /* get the raw exponent */
1195 int get_raw_exp() const
1196 {
1197 int mask;
1198 if (ebits <= 7)
1199 {
1200 /* it fits entirely in the first byte */
1201 mask = (0xff << (7 - ebits)) & 0x7f;
1202 return (int)(buf[bytes-1] & mask) >> (7 - ebits);
1203 }
1204 else if (ebits <= 15)
1205 {
1206 /* it fits in the first two bytes */
1207 int e = (int)(buf[bytes-1] & 0x7f) << (ebits - 7);
1208
1209 mask = (0xff << (15 - ebits)) & 0xff;
1210 return e | (int)(buf[bytes-2] & mask) >> (15 - ebits);
1211 }
1212 else
1213 {
1214 /* we don't currently handle anything above quad precision */
1215 assert(FALSE);
1216 return 0;
1217 }
1218 }
1219
1220 /* overall bit size (16, 32, 64, or 128) */
1221 int bits;
1222
1223 /* overall byte length */
1224 int bytes;
1225
1226 /* mantissa size in bits */
1227 int mbits;
1228
1229 /* exponent size in bits */
1230 int ebits;
1231
1232 /* minimum and maximum exponent values, and exponent bias */
1233 int emin, emax;
1234 int ebias;
1235
1236 /* our buffer - the caller provides this */
1237 unsigned char *buf;
1238 };
1239
1240 /* ------------------------------------------------------------------------ */
1241 /*
1242 * Convert to IEEE 754-2008 binary interchange format. 'bits' is the
1243 * number of bits in the format; we accept all of the standard format sizes
1244 * (16, 32, 64, 128). Our output conforms to the IEEE standard for the
1245 * format, except that we generate the buffer in the reverse byte order;
1246 * this is for consistency with the idiosyncratic TADS pack/unpack formats,
1247 * which use little-endian ordering for consistency with the standard TADS
1248 * integer interchange formats. To get the fully standard format, simply
1249 * reverse the byte order of the buffer we return.
1250 */
1251 void CVmObjBigNum::convert_to_ieee754(VMG_ char *buf, int bits, int &ov)
1252 {
1253 /* no overflow yet */
1254 ov = FALSE;
1255
1256 /* set up the buffer descriptor */
1257 ieee754 val(buf, bits);
1258
1259 /*
1260 * Check for zero, infinity, and NAN. These all have special
1261 * representations that don't follow from the arithmetic algorithm
1262 * below.
1263 */
1264 if (is_zero(ext_))
1265 {
1266 val.set_zero(get_neg(ext_));
1267 return;
1268 }
1269 else if (is_infinity(ext_))
1270 {
1271 val.set_infinity(get_neg(ext_));
1272 return;
1273 }
1274 else if (is_nan(ext_))
1275 {
1276 val.set_nan();
1277 return;
1278 }
1279
1280 /*
1281 * Figure the precision we need for our intermediate calculations. Our
1282 * most demanding calculation is the log2 of the value; we need to be
1283 * able to represent the full precision of the binary type in the
1284 * *fractional* part of the log2 result. The log2 result can have up
1285 * to the maximum exponent as the whole part, so the precision we need
1286 * for this calculation is (decimal digits of mantissa) + (decimal
1287 * digits of exponent). Add a couple of guard digits as usual so that
1288 * we don't lose significant precision in rounding in intermediate
1289 * calculations.
1290 */
1291 int prec = val.decimal_digits() + val.decimal_exp_digits() + 2;
1292
1293 /*
1294 * Set up some registers for intermediate calculations. We don't have
1295 * to allocate these since we know the upper bound to the precision
1296 * we'll need (namely 35+2 for the 128-bit type).
1297 */
1298 char t1[5+37] = { (char)prec, 0, 0, 0, 0 };
1299 char t2buf[5+37] = { (char)prec, 0, 0, 0, 0 }, *t2 = t2buf;
1300 char t3buf[5+37] = { (char)prec, 0, 0, 0, 0 }, *t3 = t3buf;
1301
1302 /*
1303 * The target format represents the number as A*2^B. Call our value N.
1304 * Observe that N == 2^(log2(N)) for any N. Let's separate out log2(N)
1305 * into its whole and fractional parts - call them W and F: so log2(N)
1306 * == W+F, which makes N == 2^(W+F) == 2^W * 2^F == 2^F * 2^W. Recall
1307 * that the format we're looking for is A*2^B, which we now have: A is
1308 * 2^F, and B is W.
1309 *
1310 * That will give us *a* binary representation of the number, but not
1311 * necessarily the canonical representation: we have to normalize by
1312 * choosing the exponent such that the implied (but not stored) first
1313 * bit of the mantissa is 1. The ln2 calculation will get us close; we
1314 * then need to adjust the exponent once we start pulling out the bits
1315 * of the mantissa.
1316 */
1317
1318 /* get/cache ln2 to the required precision */
1319 const char *ln2 = cache_ln2(prec);
1320
1321 /*
1322 * Get the absolute value of the argument. Our format and the IEEE
1323 * format both represent the value as a combination of an absolute
1324 * value and a sign, so the only thing we need to do with the sign is
1325 * to set the same sign on the result as on the input. For the log
1326 * calculation, though, we need to be working with a positive value.
1327 */
1328 copy_val(t2, ext_, TRUE);
1329 set_neg(t2, FALSE);
1330
1331 /* calculate t1=ln(self), t2=t1/ln(2) == ln2(self) */
1332 compute_ln_into(t1, t2);
1333 compute_quotient_into(t2, 0, t1, ln2);
1334
1335 /*
1336 * Get the whole part as an integer - this is the "B" value as above.
1337 * Note that this will definitely fit in a 32-bit integer type:
1338 * BigNumber stores absolute values in the range 10^-32768 to 10^32767,
1339 * so log2(self) can range from about -108000 to +108000.
1340 */
1341 copy_val(t1, t2, FALSE);
1342 compute_whole(t1);
1343 int32_t b = convert_to_int_base(t1, ov);
1344 if (get_neg(t1))
1345 b = -b;
1346
1347 /*
1348 * Calculate 2^fractional part - this is the "A" value as above. 2^y =
1349 * e^(y*ln2), so calculate t2*ln2 into t3, then e^t3 back into t2.
1350 */
1351 compute_frac(t2);
1352 compute_prod_into(t1, t2, ln2);
1353 compute_exp_into(t2, t1);
1354
1355 /*
1356 * If 'b' is less than emin-1 (the subnormal exponent value), we need
1357 * to raise it back up to emin-1. Do this by halving the mantissa and
1358 * incrementing 'b', repeating until 'b' is emin-1.
1359 *
1360 * If 'b' is less than emin-1 by more than the bit precision of the
1361 * target type, we won't have any bits to store, so store zero.
1362 */
1363 if (b < val.emin - 1 - val.mbits)
1364 {
1365 val.set_zero(get_neg(ext_));
1366 return;
1367 }
1368 while (b < val.emin - 1)
1369 {
1370 div_by_long(t2, 2);
1371 b += 1;
1372 }
1373
1374 /*
1375 * Extract the bits of the mantissa. Do this by repeatedly shifting
1376 * and subtracting: starting with divisor = 1, if decimal mantissa >=
1377 * divisor, subtract divisor and set the current bit in the output to
1378 * 1, otherwise set the output bit to 0; set divisor = divisor/2,
1379 * repeat until we've filled the output mantissa. A is 2^fraction,
1380 * where -1 < fraction < 1, so 0.5 < A < 2.
1381 *
1382 * Normalization requires that the output mantissa start with an
1383 * implied 1. This means that we ignore leading zeros; for each
1384 * leading zero, we decrement b but don't set an output bit. When we
1385 * reach the first 1 bit, we don't store it, either, since it's implied
1386 * by normalization. However, if we reach emin-1 for 'b', we're in the
1387 * subnormalization range, which means we can't decrement the exponent
1388 * any further; instead, start storing leading zeros. (Subnormal
1389 * means that the number is stored with an implied *0* leading bit, and
1390 * the special stored exponent value of emin-1, which implies an actual
1391 * exponent of emin.)
1392 */
1393 copy_val(t1, (const char *)one_, FALSE);
1394 int mbit, sig;
1395 for (mbit = 0, sig = FALSE ; mbit < val.mbits ; div_by_long(t1, 2))
1396 {
1397 /* the current bit is 1 if t2 >= t1 */
1398 if (compare_abs(t2, t1) >= 0)
1399 {
1400 /*
1401 * it's a 1 bit - if it's the first 1 bit, note that we've
1402 * found a significant bit, but don't store it, since the first
1403 * bit is implied in the output format
1404 */
1405 if (sig || b == val.emin - 1)
1406 val.set_mbit(mbit++, 1);
1407 else
1408 sig = TRUE;
1409
1410 /* subtract t2 from t1 */
1411 compute_abs_diff_into(t3, t2, t1);
1412
1413 /* swap t3 and t2 to keep the accumulator named t2 */
1414 char *ttmp = t2; t2 = t3; t3 = ttmp;
1415 }
1416 else
1417 {
1418 /*
1419 * It's a zero bit - store it if we've found a 1 already, OR
1420 * the exponent is already at the subnormal value. Otherwise
1421 * just decrement the exponent.
1422 */
1423 if (sig || b == val.emin - 1)
1424 val.set_mbit(mbit++, 0);
1425 else
1426 --b;
1427 }
1428 }
1429
1430 /*
1431 * Round the result: if the remainder is less than half of the last
1432 * bit's value (i.e., t2 < t1), round down (i.e., do nothing). If the
1433 * remainder is greater than half of the last bit's value (i.e. t2 >
1434 * t1), round up (add 1 to the low-order bit). If the remainder is
1435 * exactly half of the last bit's value, round up if the last bit was a
1436 * 1, down if it was a 0.
1437 */
1438 int r = compare_abs(t2, t1);
1439 if (r > 0 || (r == 0 && val.get_mbit(val.mbits-1)))
1440 {
1441 /* round up; if that carries out, increment the exponent */
1442 if (val.round_up())
1443 ++b;
1444 }
1445
1446 /* if 'b' wound up above the maximum for the format, it's an overflow */
1447 if (b > val.emax)
1448 {
1449 val.set_infinity(get_neg(ext_));
1450 ov = TRUE;
1451 return;
1452 }
1453
1454 /* store the final exponent and sign */
1455 val.set_exp(b);
1456 val.set_sign(get_neg(ext_));
1457 }
1458
1459
1460 /* ------------------------------------------------------------------------ */
1461 /*
1462 * Convert from IEEE 754-2008 format to BigNumber format. This takes an
1463 * IEEE 754-2008 binary interchange buffer in the given bit size (16, 32,
1464 * 64, or 128) and loads the value into the BigNumber. The buffer is in
1465 * the standard IEEE format, except that it's little endian, for
1466 * consistency with the TADS pack/unpack formats. To convert a buffer in
1467 * the fully standard IEEE format, simply reverse the byte order before
1468 * converting.
1469 */
1470 void CVmObjBigNum::set_ieee754_value(VMG_ const char *buf, int bits)
1471 {
1472 /* set up the buffer descriptor */
1473 ieee754 val((char *)buf, bits);
1474
1475 /* check for special values */
1476 if (val.is_zero())
1477 {
1478 set_zero(ext_);
1479 set_neg(ext_, val.get_sign());
1480 return;
1481 }
1482 else if (val.is_nan())
1483 {
1484 set_type(ext_, VMBN_T_NAN);
1485 return;
1486 }
1487 else if (val.is_infinity())
1488 {
1489 set_type(ext_, VMBN_T_INF);
1490 set_neg(ext_, val.get_sign());
1491 return;
1492 }
1493
1494 /*
1495 * figure the precision for our intermediate calculations based on the
1496 * precision of the source format in decimal digits
1497 */
1498 int prec = val.decimal_digits() + 2;
1499
1500 /*
1501 * Set up some registers for intermediate calculations. We don't have
1502 * to allocate these since we know the upper bound to the precision
1503 * we'll need (namely 35+2 for the 128-bit type).
1504 */
1505 char t1[5+37] = { (char)prec, 0, 0, 0, 0 };
1506 char t2buf[5+37] = { (char)prec, 0, 0, 0, 0 }, *t2 = t2buf;
1507 char t3buf[5+37] = { (char)prec, 0, 0, 0, 0 }, *t3 = t3buf;
1508
1509 /*
1510 * The IEEE value is represented as A * 2^B, for some non-zero value of
1511 * A. If the exponent is emin-1, A is represented as 0.bbbbb, where
1512 * the b's are bits of the mantissa. For any other exponent, A is
1513 * represented as 1.bbbbb. To compute our value, then, start with 2^B
1514 * in register t1 and zero in the accumulator. If the leading bit is 1
1515 * (exponent >= emin), add r1 to the accumulator. Divide t1 by 2 and
1516 * loop: if the current bit is set, add t1 to the accumulator. Repeat
1517 * for each bit of the mantissa.
1518 */
1519
1520 /* calculate t1 = 2^B = e^(B*ln2) */
1521 const char *ln2 = cache_ln2(prec);
1522 int e = val.get_exp();
1523 set_int_val(t1, e);
1524 compute_prod_into(t2, t1, ln2);
1525 compute_exp_into(t1, t2);
1526
1527 /*
1528 * If b > emin-1, there's an implied 1 bit for the whole part. If b ==
1529 * emin-1, we have a subnormal number, meaning that the implied lead
1530 * bit is 0, and the actual exponent is val.emin.
1531 */
1532 if (e > val.emin - 1)
1533 {
1534 /* normalized - add the implied leading "1" bit */
1535 copy_val(t3, t1, FALSE);
1536 }
1537 else
1538 {
1539 /*
1540 * subnormal - the implied leading bit is "0", but the actual
1541 * exponent value is emin - one higher than it appears
1542 */
1543 set_zero(t3);
1544 mul_by_long(t1, 2);
1545 }
1546
1547 /* add each bit of the mantissa */
1548 for (int i = 0 ; i < val.mbits ; ++i)
1549 {
1550 /* divide the power-of-two multiplier by 2 for the next lower place */
1551 div_by_long(t1, 2);
1552
1553 /* if this mantissa bit is 1, add t1 to the accumulator */
1554 if (val.get_mbit(i))
1555 {
1556 /* t2 <- acc + power of two */
1557 compute_sum_into(t2, t3, t1);
1558
1559 /* swap t2 and t3 so that t3 is the accumulator again */
1560 char *ttmp = t3; t3 = t2; t2 = ttmp;
1561 }
1562 }
1563
1564 /* set the sign and normalize the value */
1565 set_neg(t3, val.get_sign());
1566 normalize(t3);
1567
1568 /* copy the result into our extension */
1569 copy_val(ext_, t3, TRUE);
1570 }
1571
1572
1573
1574 /* ------------------------------------------------------------------------ */
1575 /*
1576 * Create a string representation of the number
1577 */
1578 const char *CVmObjBigNum::cast_to_string(VMG_ vm_obj_id_t self,
1579 vm_val_t *new_str) const
1580 {
1581 /* use my static method */
1582 return cvt_to_string(vmg_ self, new_str, ext_, 100, -1, -1, -1, 0, 0);
1583 }
1584
1585 /*
1586 * Convert to string with a given radix
1587 */
1588 const char *CVmObjBigNum::explicit_to_string(
1589 VMG_ vm_obj_id_t self, vm_val_t *new_str, int radix, int flags) const
1590 {
1591 /*
1592 * If they want a non-decimal conversion, and we're a whole integer
1593 * without a fractional part, generate the integer representation in
1594 * the given radix. If we have a fractional part, or the requested
1595 * radix is decimal, use the floating-point formatter instead.
1596 *
1597 * Also use an integer conversion if we've been specfically asked for
1598 * an integer conversion.
1599 */
1600 if ((radix != 10 && is_frac_zero(ext_))
1601 || (flags & TOSTR_ROUND) != 0)
1602 {
1603 /*
1604 * it's all integer, and we have a non-decimal radix - format as an
1605 * integer
1606 */
1607 return cvt_to_string_in_radix(vmg_ self, new_str, radix);
1608 }
1609 else
1610 {
1611 /*
1612 * no radix, or we have a fraction - use the basic floating-point
1613 * formatter with default options
1614 */
1615 return cvt_to_string(vmg_ self, new_str, ext_, 100, -1, -1, -1, 0, 0);
1616 }
1617 }
1618
1619 /* ------------------------------------------------------------------------ */
1620 /*
1621 * String buffer allocator
1622 */
1623 char *CBigNumStringBufAlo::get_buf(size_t need)
1624 {
1625 /* use the fixed buffer if it's big enough */
1626 if (len >= need)
1627 return buf;
1628
1629 /* the fixed buffer isn't big enough, so allocate a new string */
1630 if (strval != 0)
1631 {
1632 VMGLOB_PTR(vmg);
1633 return CVmObjString::alloc_str_buf(vmg_ strval, 0, 0, need);
1634 }
1635
1636 /* the buffer's too small, and we can't allocate, so fail */
1637 return 0;
1638 }
1639
1640 /* ------------------------------------------------------------------------ */
1641 /*
1642 * convert to a string, storing the result in the given buffer if it'll
1643 * fit, otherwise in a new string
1644 */
1645 const char *CVmObjBigNum::cvt_to_string_buf(
1646 VMG_ vm_val_t *new_str, char *buf, size_t buflen,
1647 int max_digits, int whole_places, int frac_digits, int exp_digits,
1648 ulong flags)
1649 {
1650 /* set up an allocator */
1651 CBigNumStringBufAlo alo(vmg_ new_str, buf, buflen);
1652
1653 /* convert to a string into our buffer */
1654 return cvt_to_string_gen(
1655 &alo, ext_, max_digits, whole_places, frac_digits, exp_digits,
1656 flags, 0, 0);
1657 }
1658
1659 /* ------------------------------------------------------------------------ */
1660 /*
1661 * Convert to a string, creating a new string object to hold the result
1662 */
1663 const char *CVmObjBigNum::cvt_to_string(
1664 VMG_ vm_obj_id_t self, vm_val_t *new_str, const char *ext,
1665 int max_digits, int whole_places, int frac_digits, int exp_digits,
1666 ulong flags, vm_val_t *lead_fill)
1667 {
1668 /* push a self-reference for gc protection during allocation */
1669 G_stk->push()->set_obj(self);
1670
1671 /* set up an allocator */
1672 CBigNumStringBufAlo alo(vmg_ new_str);
1673
1674 /* if there's a lead fill parameter, get its string value */
1675 const char *lead_fill_str = 0;
1676 size_t lead_fill_len = 0;
1677 if (lead_fill != 0 && lead_fill->typ != VM_NIL)
1678 {
1679 /* get the string value */
1680 lead_fill_str = lead_fill->get_as_string(vmg0_);
1681
1682 /* if it's not a string, it's an error */
1683 if (lead_fill_str == 0)
1684 err_throw(VMERR_STRING_VAL_REQD);
1685
1686 /* read and skip the length prefix */
1687 lead_fill_len = vmb_get_len(lead_fill_str);
1688 lead_fill_str += VMB_LEN;
1689
1690 /* if the length is zero, ignore the lead fill string entirely */
1691 if (lead_fill_len == 0)
1692 lead_fill_str = 0;
1693 }
1694
1695 /*
1696 * convert to a string - don't pass in a buffer, since we want to
1697 * create a new string to hold the result
1698 */
1699 const char *ret = cvt_to_string_gen(
1700 &alo, ext, max_digits, whole_places, frac_digits, exp_digits,
1701 flags, lead_fill_str, lead_fill_len);
1702
1703 /* discard our gc protection */
1704 G_stk->discard();
1705
1706 /* return the result */
1707 return ret;
1708 }
1709
1710 /* ------------------------------------------------------------------------ */
1711 /*
1712 * Convert an integer value to a string in the given radix (2-36)
1713 */
1714 const char *CVmObjBigNum::cvt_to_string_in_radix(
1715 VMG_ vm_obj_id_t self, vm_val_t *new_str, int radix) const
1716 {
1717 /* check for special values: zeros, NaNs, and infinities */
1718 const char *fixed = 0;
1719 int neg = get_neg(ext_);
1720 if (is_zero(ext_))
1721 {
1722 /* show zero as "0" in all bases */
1723 fixed = "0";
1724 }
1725 else if (is_infinity(ext_))
1726 {
1727 /*
1728 * show infinity as "1.#INF" for positive or unsigned, "-1.#INF"
1729 * for negative infinity
1730 */
1731 fixed = (neg ? "-1.#INF" : "1.#INF");
1732 }
1733 else if (is_nan(ext_))
1734 {
1735 /* not a number */
1736 fixed = "1.#NAN";
1737 }
1738 else
1739 {
1740 /* make a temporary copy of the number */
1741 uint thdl;
1742 char *tmp = alloc_temp_reg(get_prec(ext_), &thdl);
1743 err_try
1744 {
1745 /* copy the value into our temporary register */
1746 copy_val(tmp, ext_, FALSE);
1747
1748 /* if there's a fractional part, round to integer */
1749 round_to_int(tmp);
1750
1751 /*
1752 * It's an ordinary non-zero number. Figure how many digits
1753 * the integer portion will take in the given radix. This is
1754 * fairly simple: a D digit number in decimal requires
1755 * D/log10(R) digits in base R, rounding up. Our storage
1756 * format makes it easy to determine D - it's simply our
1757 * base-10 exponent.
1758 */
1759 int len = (int)ceil(get_exp(ext_) / log10((double)radix));
1760
1761 /* if the value is zero, we need one digit for the zero */
1762 if (len == 0)
1763 len = 1;
1764
1765 /* if it's negative, add space for the '-' */
1766 if (neg)
1767 len += 1;
1768
1769 /* create the string */
1770 new_str->set_obj(CVmObjString::create(vmg_ FALSE, len));
1771 CVmObjString *str = (CVmObjString *)vm_objp(vmg_ new_str->val.obj);
1772 char *buf = str->cons_get_buf(), *p = buf;
1773
1774 /* add the '-' sign if negative */
1775 if (neg)
1776 {
1777 *p++ = '-';
1778 ++buf;
1779 --len;
1780 }
1781
1782 /* generate the digits */
1783 while (!is_zero(tmp) && p - buf < len)
1784 {
1785 /* get the next digit */
1786 unsigned long rem;
1787 div_by_long(tmp, radix, &rem);
1788
1789 /* add it to the output */
1790 *p++ = (char)(rem < 10 ? rem + '0' : rem - 10 + 'A');
1791 }
1792
1793 /*
1794 * We just generated the digits in reverse order. Reverse the
1795 * string so that they're in the right order.
1796 */
1797 char *p1, *p2, tmp;
1798 for (p1 = buf, p2 = p - 1 ; p2 > p1 ; --p2, ++p1)
1799 tmp = *p1, *p1 = *p2, *p2 = tmp;
1800
1801 /* if we generated no digits, generate a zero */
1802 if (p == buf)
1803 *p++ = '0';
1804
1805 /* set the final length, in case rounding left us off by one */
1806 str->cons_set_len(p - str->cons_get_buf());
1807 }
1808 err_finally
1809 {
1810 /* release our temporary register */
1811 release_temp_reg(thdl);
1812 }
1813 err_end;
1814 }
1815
1816 /* if we came up with a fixed source string, create the string object */
1817 if (fixed != 0)
1818 new_str->set_obj(CVmObjString::create(
1819 vmg_ FALSE, fixed, strlen(fixed)));
1820
1821 /* return the new string buffer */
1822 return new_str->get_as_string(vmg0_);
1823 }
1824
1825 /* ------------------------------------------------------------------------ */
1826 /*
1827 * save to a file
1828 */
1829 void CVmObjBigNum::save_to_file(VMG_ class CVmFile *fp)
1830 {
1831 size_t prec;
1832
1833 /* get our precision */
1834 prec = get_prec(ext_);
1835
1836 /* write the data */
1837 fp->write_bytes(ext_, calc_alloc(prec));
1838 }
1839
1840 /*
1841 * restore from a file
1842 */
1843 void CVmObjBigNum::restore_from_file(VMG_ vm_obj_id_t,
1844 CVmFile *fp, CVmObjFixup *)
1845 {
1846 size_t prec;
1847
1848 /* read the precision */
1849 prec = fp->read_uint2();
1850
1851 /* free any existing extension */
1852 if (ext_ != 0)
1853 {
1854 G_mem->get_var_heap()->free_mem(ext_);
1855 ext_ = 0;
1856 }
1857
1858 /* allocate the space */
1859 alloc_bignum(vmg_ prec);
1860
1861 /* store our precision */
1862 set_prec(ext_, prec);
1863
1864 /* read the contents */
1865 fp->read_bytes(ext_ + VMBN_EXP, calc_alloc(prec) - VMBN_EXP);
1866 }
1867
1868
1869 /* ------------------------------------------------------------------------ */
1870 /*
1871 * set a property
1872 */
1873 void CVmObjBigNum::set_prop(VMG_ class CVmUndo *,
1874 vm_obj_id_t, vm_prop_id_t,
1875 const vm_val_t *)
1876 {
1877 /* we have no properties to set */
1878 err_throw(VMERR_INVALID_SETPROP);
1879 }
1880
1881 /*
1882 * get a static property
1883 */
1884 int CVmObjBigNum::call_stat_prop(VMG_ vm_val_t *result, const uchar **pc_ptr,
1885 uint *argc, vm_prop_id_t prop)
1886 {
1887 /* translate the property into a function vector index */
1888 switch(G_meta_table
1889 ->prop_to_vector_idx(metaclass_reg_->get_reg_idx(), prop))
1890 {
1891 case VMOBJBN_GET_PI:
1892 return s_getp_pi(vmg_ result, argc);
1893
1894 case VMOBJBN_GET_E:
1895 return s_getp_e(vmg_ result, argc);
1896
1897 default:
1898 /*
1899 * we don't define this one - inherit the default from the base
1900 * object metaclass
1901 */
1902 return CVmObject::call_stat_prop(vmg_ result, pc_ptr, argc, prop);
1903 }
1904 }
1905
1906 /*
1907 * get a property
1908 */
1909 int CVmObjBigNum::get_prop(VMG_ vm_prop_id_t prop, vm_val_t *val,
1910 vm_obj_id_t self, vm_obj_id_t *source_obj,
1911 uint *argc)
1912 {
1913 uint func_idx;
1914
1915 /* translate the property into a function vector index */
1916 func_idx = G_meta_table
1917 ->prop_to_vector_idx(metaclass_reg_->get_reg_idx(), prop);
1918
1919 /* call the function */
1920 if ((this->*func_table_[func_idx])(vmg_ self, val, argc))
1921 {
1922 *source_obj = metaclass_reg_->get_class_obj(vmg0_);
1923 return TRUE;
1924 }
1925
1926 /* inherit default handling */
1927 return CVmObject::get_prop(vmg_ prop, val, self, source_obj, argc);
1928 }
1929
1930 /*
1931 * Property evaluator - formatString
1932 */
1933 int CVmObjBigNum::getp_format(VMG_ vm_obj_id_t self,
1934 vm_val_t *retval, uint *argc)
1935 {
1936 int orig_argc = (argc != 0 ? *argc : 0);
1937 int max_digits = -1;
1938 uint flags = 0;
1939 int whole_places = -1;
1940 int frac_digits = -1;
1941 int exp_digits = -1;
1942 vm_val_t *lead_fill = 0;
1943 static CVmNativeCodeDesc desc(0, 6);
1944
1945 /* check arguments */
1946 if (get_prop_check_argc(retval, argc, &desc))
1947 return TRUE;
1948
1949 /* get the maximum digit count */
1950 if (orig_argc >= 1)
1951 max_digits = CVmBif::pop_int_or_nil(vmg_ -1);
1952
1953 /* get the flags */
1954 if (orig_argc >= 2)
1955 flags = CVmBif::pop_int_or_nil(vmg_ 0);
1956
1957 /* get the whole places */
1958 if (orig_argc >= 3)
1959 whole_places = CVmBif::pop_int_or_nil(vmg_ -1);
1960
1961 /* get the fraction digits */
1962 if (orig_argc >= 4)
1963 frac_digits = CVmBif::pop_int_or_nil(vmg_ -1);
1964
1965 /* get the exponent digits */
1966 if (orig_argc >= 5)
1967 exp_digits = CVmBif::pop_int_or_nil(vmg_ -1);
1968
1969 /*
1970 * get the lead fill string if provided (leave it on the stack to
1971 * protect against garbage collection)
1972 */
1973 if (orig_argc >= 6)
1974 lead_fill = G_stk->get(0);
1975
1976 /* format the number, which will build the return string */
1977 cvt_to_string(vmg_ self, retval, ext_, max_digits, whole_places,
1978 frac_digits, exp_digits, flags, lead_fill);
1979
1980 /* discard the lead fill string, if provided */
1981 if (lead_fill != 0)
1982 G_stk->discard();
1983
1984 /* handled */
1985 return TRUE;
1986 }
1987
1988 /*
1989 * Property eval - equal after rounding
1990 */
1991 int CVmObjBigNum::getp_equal_rnd(VMG_ vm_obj_id_t self,
1992 vm_val_t *retval, uint *argc)
1993 {
1994 vm_val_t val2;
1995 static CVmNativeCodeDesc desc(1);
1996
1997 /* check arguments */
1998 if (get_prop_check_argc(retval, argc, &desc))
1999 return TRUE;
2000
2001 /* pop the value to compare */
2002 G_stk->pop(&val2);
2003
2004 /* convert it to BigNumber */
2005 if (!cvt_to_bignum(vmg_ self, &val2))
2006 {
2007 /* it's not a BigNumber, so it's not equal */
2008 retval->set_nil();
2009 }
2010 else
2011 {
2012 int ret;
2013
2014 /* test for equality */
2015 ret = compute_eq_round(vmg_ ext_, get_objid_ext(vmg_ val2.val.obj));
2016
2017 /* set the return value */
2018 retval->set_logical(ret);
2019 }
2020
2021 /* handled */
2022 return TRUE;
2023 }
2024
2025 /*
2026 * property eval - get the precision
2027 */
2028 int CVmObjBigNum::getp_get_prec(VMG_ vm_obj_id_t self,
2029 vm_val_t *retval, uint *argc)
2030 {
2031 static CVmNativeCodeDesc desc(0);
2032
2033 /* check arguments */
2034 if (get_prop_check_argc(retval, argc, &desc))
2035 return TRUE;
2036
2037 /* return an integer giving my precision */
2038 retval->set_int(get_prec(ext_));
2039
2040 /* handled */
2041 return TRUE;
2042 }
2043
2044 /*
2045 * property eval - set the precision
2046 */
2047 int CVmObjBigNum::getp_set_prec(VMG_ vm_obj_id_t self,
2048 vm_val_t *retval, uint *argc)
2049 {
2050 size_t digits;
2051 static CVmNativeCodeDesc desc(1);
2052
2053 /* check arguments */
2054 if (get_prop_check_argc(retval, argc, &desc))
2055 return TRUE;
2056
2057 /* get the number of digits for rounding */
2058 digits = CVmBif::pop_int_val(vmg0_);
2059
2060 /* if I'm not a number, return myself unchanged */
2061 if (is_nan(ext_))
2062 {
2063 retval->set_obj(self);
2064 return TRUE;
2065 }
2066
2067 /* push a self-reference while we're working */
2068 G_stk->push()->set_obj(self);
2069
2070 /* create the rounded value */
2071 round_val(vmg_ retval, ext_, digits, TRUE);
2072
2073 /* remove my self-reference */
2074 G_stk->discard();
2075
2076 /* handled */
2077 return TRUE;
2078 }
2079
2080 /*
2081 * get pi (static method)
2082 */
2083 int CVmObjBigNum::s_getp_pi(VMG_ vm_val_t *val, uint *argc)
2084 {
2085 size_t prec;
2086 char *new_ext;
2087 const char *pi;
2088 static CVmNativeCodeDesc desc(1);
2089
2090 /* check arguments */
2091 if (get_prop_check_argc(val, argc, &desc))
2092 return TRUE;
2093
2094 /* get the precision argument */
2095 prec = CVmBif::pop_int_val(vmg0_);
2096
2097 /* allocate the result */
2098 val->set_obj(create(vmg_ FALSE, prec));
2099 new_ext = get_objid_ext(vmg_ val->val.obj);
2100
2101 /* cache pi to the required precision */
2102 pi = cache_pi(prec);
2103
2104 /* return the value */
2105 copy_val(new_ext, pi, TRUE);
2106
2107 /* handled */
2108 return TRUE;
2109 }
2110
2111 /*
2112 * get e (static method)
2113 */
2114 int CVmObjBigNum::s_getp_e(VMG_ vm_val_t *val, uint *argc)
2115 {
2116 size_t prec;
2117 char *new_ext;
2118 const char *e;
2119 static CVmNativeCodeDesc desc(1);
2120
2121 /* check arguments */
2122 if (get_prop_check_argc(val, argc, &desc))
2123 return TRUE;
2124
2125 /* get the precision argument */
2126 prec = CVmBif::pop_int_val(vmg0_);
2127
2128 /* allocate the result */
2129 val->set_obj(create(vmg_ FALSE, prec));
2130 new_ext = get_objid_ext(vmg_ val->val.obj);
2131
2132 /* cache e to the required precision */
2133 e = cache_e(prec);
2134
2135 /* return the value */
2136 copy_val(new_ext, e, TRUE);
2137
2138 /* handled */
2139 return TRUE;
2140 }
2141
2142 /*
2143 * Set up for a zero-argument operation that returns a BigNumber result.
2144 * Returns true if the argument check indicates that the caller should
2145 * simply return to its caller, false if the caller should proceed.
2146 *
2147 * After checking the argument count, we'll proceed to set up the return
2148 * value as per setup_getp_retval().
2149 */
2150 int CVmObjBigNum::setup_getp_0(VMG_ vm_obj_id_t self, vm_val_t *retval,
2151 uint *argc, char **new_ext)
2152 {
2153 /* check arguments */
2154 static CVmNativeCodeDesc desc(0);
2155 if (get_prop_check_argc(retval, argc, &desc))
2156 return TRUE;
2157
2158 /* set up the return value */
2159 return setup_getp_retval(vmg_ self, retval, new_ext, get_prec(ext_));
2160 }
2161
2162 /*
2163 * Set up for a one-argument operation that takes a BigNumber value as
2164 * the argument and returns a BigNumber result. Does the work of
2165 * setup_getp_0, but also pops the argument value and converts it to a
2166 * BigNumber (throwing an error if the value is not convertible).
2167 *
2168 * Fills in val2 with the argument value, and fills in *ext2 with val2's
2169 * extension buffer.
2170 *
2171 * The result value will have the larger of the precisions of self and
2172 * the other value, unless use_self_prec is set, in which case we'll use
2173 * self's precision unconditionally.
2174 *
2175 * If either argument is not a number, we'll set the return value to the
2176 * not-a-number argument unchanged, and return true.
2177 */
2178 int CVmObjBigNum::setup_getp_1(VMG_ vm_obj_id_t self,
2179 vm_val_t *retval, uint *argc,
2180 char **new_ext,
2181 vm_val_t *val2, const char **ext2,
2182 int use_self_prec)
2183 {
2184 /* check arguments */
2185 static CVmNativeCodeDesc desc(1);
2186 if (get_prop_check_argc(retval, argc, &desc))
2187 return TRUE;
2188
2189 /* pop the argument value */
2190 G_stk->pop(val2);
2191
2192 /* convert it to BigNumber */
2193 if (!cvt_to_bignum(vmg_ self, val2))
2194 {
2195 /* it's not a BigNumber - throw an error */
2196 err_throw(VMERR_BAD_TYPE_BIF);
2197 }
2198
2199 /* get the other value's extension */
2200 *ext2 = get_objid_ext(vmg_ val2->val.obj);
2201
2202 /* if the other value is not a number, return it as the result */
2203 if (is_nan(*ext2))
2204 {
2205 retval->set_obj(val2->val.obj);
2206 return TRUE;
2207 }
2208
2209 /*
2210 * if val2's precision is higher than ours, use it, unless we've
2211 * been specifically told to use our own precision for the result
2212 */
2213 size_t prec = get_prec(ext_);
2214 if (!use_self_prec && get_prec(*ext2) > prec)
2215 prec = get_prec(*ext2);
2216
2217 /* push the other result to protect it from garbage collection */
2218 G_stk->push(val2);
2219
2220 /* allocate the return value */
2221 if (setup_getp_retval(vmg_ self, retval, new_ext, prec))
2222 {
2223 /* discard the val2 reference we pushed for gc protection */
2224 G_stk->discard();
2225
2226 /* tell the caller we're done */
2227 return TRUE;
2228 }
2229
2230 /* tell the caller to proceed */
2231 return FALSE;
2232 }
2233
2234 /*
2235 * Set up for an operation that returns a BigNumber result. Returns
2236 * true if we finished the operation, in which case the caller should
2237 * simply return; returns false if the operation should still be carried
2238 * out, in which case the caller should proceed as normal.
2239 *
2240 * If the 'self' value is not-a-number, we'll return it as the result
2241 * (and return true to indicate that no further processing is required).
2242 *
2243 * If we return false, we'll have pushed a reference to 'self' onto the
2244 * stack for protection against garbage collection. The caller must
2245 * discard this reference before returning. We push no such
2246 * self-reference if we return true.
2247 *
2248 * In addition, if we return false, we'll fill in '*new_ext' with a
2249 * pointer to the extension buffer for the return value object that we
2250 * allocate. We'll allocate the return value with the same precision as
2251 * 'self'.
2252 *
2253 * Note that the caller should ensure that any argument sare removed
2254 * from the stack before calling this routine, since we might push the
2255 * self-reference onto the stack.
2256 */
2257 int CVmObjBigNum::setup_getp_retval(VMG_ vm_obj_id_t self,
2258 vm_val_t *retval, char **new_ext,
2259 size_t prec)
2260 {
2261 /* if I'm not a number, return myself unchanged */
2262 if (is_nan(ext_))
2263 {
2264 retval->set_obj(self);
2265 return TRUE;
2266 }
2267
2268 /* push a self-reference while we're working */
2269 G_stk->push()->set_obj(self);
2270
2271 /* create a new number with the same precision as the original */
2272 retval->set_obj(create(vmg_ FALSE, prec));
2273 *new_ext = get_objid_ext(vmg_ retval->val.obj);
2274
2275 /* tell the caller to proceed */
2276 return FALSE;
2277 }
2278
2279 /*
2280 * property eval - get the fractional part
2281 */
2282 int CVmObjBigNum::getp_frac(VMG_ vm_obj_id_t self,
2283 vm_val_t *retval, uint *argc)
2284 {
2285 char *new_ext;
2286
2287 /* check arguments and allocate the result value */
2288 if (setup_getp_0(vmg_ self, retval, argc, &new_ext))
2289 return TRUE;
2290
2291 /* make a copy in the new object, and get the fractional portion */
2292 memcpy(new_ext, ext_, calc_alloc(get_prec(ext_)));
2293 compute_frac(new_ext);
2294
2295 /* remove my self-reference */
2296 G_stk->discard();
2297
2298 /* handled */
2299 return TRUE;
2300 }
2301
2302 /*
2303 * property eval - get the whole part, with no rounding
2304 */
2305 int CVmObjBigNum::getp_whole(VMG_ vm_obj_id_t self,
2306 vm_val_t *retval, uint *argc)
2307 {
2308 char *new_ext;
2309
2310 /* check arguments and allocate the result value */
2311 if (setup_getp_0(vmg_ self, retval, argc, &new_ext))
2312 return TRUE;
2313
2314 /* make a copy in the new object, and get the whole part */
2315 memcpy(new_ext, ext_, calc_alloc(get_prec(ext_)));
2316 compute_whole(new_ext);
2317
2318 /* remove my self-reference */
2319 G_stk->discard();
2320
2321 /* handled */
2322 return TRUE;
2323 }
2324
2325 /*
2326 * property eval - round to a given number of decimal places
2327 */
2328 int CVmObjBigNum::getp_round_dec(VMG_ vm_obj_id_t self,
2329 vm_val_t *retval, uint *argc)
2330 {
2331 int places;
2332 char *new_ext;
2333 int post_idx;
2334 int exp = get_exp(ext_);
2335 size_t prec = get_prec(ext_);
2336 static CVmNativeCodeDesc desc(1);
2337
2338 /* check arguments */
2339 if (get_prop_check_argc(retval, argc, &desc))
2340 return TRUE;
2341
2342 /* get the number of digits for rounding */
2343 places = CVmBif::pop_int_val(vmg0_);
2344
2345 /* set up the return value */
2346 if (setup_getp_retval(vmg_ self, retval, &new_ext, prec))
2347 return TRUE;
2348
2349 /* make a copy in the new object */
2350 memcpy(new_ext, ext_, calc_alloc(prec));
2351
2352 /*
2353 * Determine if the first digit we're lopping off is actually
2354 * represented in the number or not. This digit position is the
2355 * exponent plus the number of decimal places after the decimal to
2356 * keep - if this value is at least zero and less than the
2357 * precision, it's part of the number.
2358 */
2359 post_idx = places + exp;
2360 if (post_idx < 0)
2361 {
2362 /*
2363 * the digit after the last digit to keep is actually before the
2364 * beginning of the number, so the result of the rounding is
2365 * simply zero
2366 */
2367 set_zero(new_ext);
2368 }
2369 else if (post_idx >= (int)prec)
2370 {
2371 /*
2372 * the digit after the last digit to keep is past the end of the
2373 * represented digits, so rounding has no effect at all - we'll
2374 * simply return the same number
2375 */
2376 }
2377 else
2378 {
2379 /* round it */
2380 round_to(new_ext, post_idx);
2381
2382 /* normalize the result */
2383 normalize(new_ext);
2384 }
2385
2386 /* remove my self-reference */
2387 G_stk->discard();
2388
2389 /* handled */
2390 return TRUE;
2391 }
2392
2393 /*
2394 * property eval - get the absolute value
2395 */
2396 int CVmObjBigNum::getp_abs(VMG_ vm_obj_id_t self,
2397 vm_val_t *retval, uint *argc)
2398 {
2399 /* check arguments */
2400 static CVmNativeCodeDesc desc(0);
2401 if (get_prop_check_argc(retval, argc, &desc))
2402 return TRUE;
2403
2404 /* compute the absolute value */
2405 abs_val(vmg_ retval, self);
2406
2407 /* handled */
2408 return TRUE;
2409 }
2410
2411 /*
2412 * absolute value
2413 */
2414 int CVmObjBigNum::abs_val(VMG_ vm_val_t *retval, vm_obj_id_t self)
2415 {
2416 /*
2417 * If I'm not an ordinary number or an infinity, or I'm already
2418 * non-negative, return myself unchanged. Note that we change negative
2419 * infinity to infinity, even though this might not make a great deal
2420 * of sense mathematically.
2421 */
2422 if (!get_neg(ext_)
2423 || (get_type(ext_) != VMBN_T_NUM && get_type(ext_) != VMBN_T_INF))
2424 {
2425 retval->set_obj(self);
2426 return TRUE;
2427 }
2428
2429 /* push a self-reference while we're working */
2430 G_stk->push()->set_obj(self);
2431
2432 /*
2433 * if I'm negative infinity, we don't need any precision in the new
2434 * value; otherwise use my original precision
2435 */
2436 size_t prec = (is_infinity(ext_) ? 1 : get_prec(ext_));
2437
2438 /* create a new number with the same precision as the original */
2439 retval->set_obj(create(vmg_ FALSE, prec));
2440 char *new_ext = get_objid_ext(vmg_ retval->val.obj);
2441
2442 /* make a copy in the new object */
2443 memcpy(new_ext, ext_, calc_alloc(prec));
2444
2445 /* set the sign to positive */
2446 set_neg(new_ext, FALSE);
2447
2448 /* remove my self-reference */
2449 G_stk->discard();
2450
2451 /* success */
2452 return TRUE;
2453 }
2454
2455 /*
2456 * compute the sgn value
2457 */
2458 int CVmObjBigNum::sgn_val(VMG_ vm_val_t *retval, vm_obj_id_t self)
2459 {
2460 /* figure the sgn value */
2461 if (is_zero(ext_))
2462 retval->set_int(0);
2463 else if (get_neg(ext_))
2464 retval->set_int(-1);
2465 else
2466 retval->set_int(1);
2467
2468 /* success */
2469 return TRUE;
2470 }
2471
2472 /*
2473 * property eval - ceiling (least integer greater than or equal to self)
2474 */
2475 int CVmObjBigNum::getp_ceil(VMG_ vm_obj_id_t self,
2476 vm_val_t *retval, uint *argc)
2477 {
2478 char *new_ext;
2479 size_t idx;
2480 int exp = get_exp(ext_);
2481 size_t prec = get_prec(ext_);
2482 int frac_zero;
2483 static CVmNativeCodeDesc desc(0);
2484
2485 /* check arguments */
2486 if (get_prop_check_argc(retval, argc, &desc))
2487 return TRUE;
2488
2489 /* check arguments and allocate the result value */
2490 if (setup_getp_0(vmg_ self, retval, argc, &new_ext))
2491 return TRUE;
2492
2493 /* make a copy in the new object */
2494 memcpy(new_ext, ext_, calc_alloc(prec));
2495
2496 /* determine if the fractional part is non-zero */
2497 frac_zero = is_frac_zero(new_ext);
2498
2499 /* check what we have */
2500 if (exp <= 0)
2501 {
2502 /*
2503 * it's an entirely fractional number - the result is zero if
2504 * the number is negative or zero, one if the number is positive
2505 */
2506 if (get_neg(new_ext) || frac_zero)
2507 {
2508 /* -1 < x <= 0 -> ceil(x) = 0 */
2509 set_zero(new_ext);
2510 }
2511 else
2512 {
2513 /* 0 < x < 1 -> ceil(x) = 1 */
2514 copy_val(new_ext, get_one(), FALSE);
2515 }
2516 }
2517 else
2518 {
2519 /* clear digits after the decimal point */
2520 for (idx = (size_t)exp ; idx < prec ; ++idx)
2521 set_dig(new_ext, idx, 0);
2522
2523 /*
2524 * if there's a fractional part and it's positive, increment the
2525 * number
2526 */
2527 if (!frac_zero && !get_neg(new_ext))
2528 increment_abs(new_ext);
2529 }
2530
2531 /* remove my self-reference */
2532 G_stk->discard();
2533
2534 /* handled */
2535 return TRUE;
2536 }
2537
2538 /*
2539 * property eval - floor (greatest integer <= self)
2540 */
2541 int CVmObjBigNum::getp_floor(VMG_ vm_obj_id_t self,
2542 vm_val_t *retval, uint *argc)
2543 {
2544 char *new_ext;
2545 size_t idx;
2546 int exp = get_exp(ext_);
2547 size_t prec = get_prec(ext_);
2548 int frac_zero;
2549
2550 /* check arguments and allocate the result value */
2551 if (setup_getp_0(vmg_ self, retval, argc, &new_ext))
2552 return TRUE;
2553
2554 /* make a copy in the new object */
2555 memcpy(new_ext, ext_, calc_alloc(prec));
2556
2557 /* determine if the fractional part is non-zero */
2558 frac_zero = is_frac_zero(new_ext);
2559
2560 /* check what we have */
2561 if (exp <= 0)
2562 {
2563 /*
2564 * it's an entirely fractional number - the result is zero if
2565 * the number is positive or zero, -1 if the number is negative
2566 */
2567 if (!get_neg(new_ext) || frac_zero)
2568 {
2569 /* 0 <= x < 1 -> floor(x) = 0 */
2570 set_zero(new_ext);
2571 }
2572 else
2573 {
2574 /* -1 < x < 0 -> floor(x) = -1 */
2575 copy_val(new_ext, get_one(), FALSE);
2576 set_neg(new_ext, TRUE);
2577 }
2578 }
2579 else
2580 {
2581 /* clear digits after the decimal point */
2582 for (idx = (size_t)exp ; idx < prec ; ++idx)
2583 set_dig(new_ext, idx, 0);
2584
2585 /*
2586 * if there's a fractional part and the number is negative,
2587 * increment the number's absolute value
2588 */
2589 if (!frac_zero && get_neg(new_ext))
2590 increment_abs(new_ext);
2591 }
2592
2593 /* remove my self-reference */
2594 G_stk->discard();
2595
2596 /* handled */
2597 return TRUE;
2598 }
2599
2600 /*
2601 * property eval - getScale
2602 */
2603 int CVmObjBigNum::getp_get_scale(VMG_ vm_obj_id_t self,
2604 vm_val_t *retval, uint *argc)
2605 {
2606 static CVmNativeCodeDesc desc(0);
2607
2608 /* check arguments */
2609 if (get_prop_check_argc(retval, argc, &desc))
2610 return TRUE;
2611
2612 /* check the type */
2613 if (is_nan(ext_))
2614 {
2615 /* it's not a number - return nil for the scale */
2616 retval->set_nil();
2617 }
2618 else
2619 {
2620 /* return an integer giving the number's scale */
2621 retval->set_int(get_exp(ext_));
2622 }
2623
2624 /* handled */
2625 return TRUE;
2626 }
2627
2628 /*
2629 * property eval - scale
2630 */
2631 int CVmObjBigNum::getp_scale(VMG_ vm_obj_id_t self,
2632 vm_val_t *retval, uint *argc)
2633 {
2634 char *new_ext;
2635 size_t prec = get_prec(ext_);
2636 int scale;
2637 static CVmNativeCodeDesc desc(1);
2638
2639 /* check arguments */
2640 if (get_prop_check_argc(retval, argc, &desc))
2641 return TRUE;
2642
2643 /* get the scaling argument */
2644 scale = CVmBif::pop_int_val(vmg0_);
2645
2646 /* set up the return value */
2647 if (setup_getp_retval(vmg_ self, retval, &new_ext, prec))
2648 return TRUE;
2649
2650 /* copy the value */
2651 memcpy(new_ext, ext_, calc_alloc(prec));
2652
2653 /* adjust the exponent by the scale factor */
2654 set_exp(new_ext, get_exp(new_ext) + scale);
2655
2656 /* discard the GC protection */
2657 G_stk->discard();
2658
2659 /* handled */
2660 return TRUE;
2661 }
2662
2663 /*
2664 * property eval - negate
2665 */
2666 int CVmObjBigNum::getp_negate(VMG_ vm_obj_id_t self,
2667 vm_val_t *retval, uint *argc)
2668 {
2669 static CVmNativeCodeDesc desc(0);
2670
2671 /* check arguments */
2672 if (get_prop_check_argc(retval, argc, &desc))
2673 return TRUE;
2674
2675 /* negate the value */
2676 neg_val(vmg_ retval, self);
2677
2678 /* handled */
2679 return TRUE;
2680 }
2681
2682 /*
2683 * property eval - copy sign
2684 */
2685 int CVmObjBigNum::getp_copy_sign(VMG_ vm_obj_id_t self,
2686 vm_val_t *retval, uint *argc)
2687 {
2688 vm_val_t val2;
2689 char *new_ext;
2690 const char *ext2;
2691 size_t prec = get_prec(ext_);
2692
2693 if (setup_getp_1(vmg_ self, retval, argc, &new_ext,
2694 &val2, &ext2, TRUE))
2695 return TRUE;
2696
2697 /* make a copy of my value in the new object */
2698 memcpy(new_ext, ext_, calc_alloc(prec));
2699
2700 /* set the sign from the other object */
2701 set_neg(new_ext, get_neg(ext2));
2702
2703 /*
2704 * normalize it (this is important when the value was zero to start
2705 * with, since zero is always represented without a negative sign)
2706 */
2707 normalize(new_ext);
2708
2709 /* remove the GC protection */
2710 G_stk->discard(2);
2711
2712 /* handled */
2713 return TRUE;
2714 }
2715
2716 /*
2717 * property eval - isNegative
2718 */
2719 int CVmObjBigNum::getp_is_neg(VMG_ vm_obj_id_t self,
2720 vm_val_t *retval, uint *argc)
2721 {
2722 static CVmNativeCodeDesc desc(0);
2723
2724 /* check arguments */
2725 if (get_prop_check_argc(retval, argc, &desc))
2726 return TRUE;
2727
2728 /* if I'm not an ordinary number or an infinity, I'm not negative */
2729 if (get_type(ext_) != VMBN_T_NUM && get_type(ext_) != VMBN_T_INF)
2730 {
2731 /* I'm not negative, so return nil */
2732 retval->set_nil();
2733 }
2734 else
2735 {
2736 /* set the return value to true if I'm negative, nil if not */
2737 retval->set_logical(get_neg(ext_));
2738 }
2739
2740 /* handled */
2741 return TRUE;
2742 }
2743
2744 /*
2745 * property eval - remainder
2746 */
2747 int CVmObjBigNum::getp_remainder(VMG_ vm_obj_id_t self,
2748 vm_val_t *retval, uint *argc)
2749 {
2750 vm_val_t val2;
2751 const char *ext2;
2752 char *quo_ext;
2753 char *rem_ext;
2754 vm_val_t rem_val;
2755 vm_val_t quo_val;
2756 CVmObjList *lst;
2757 static CVmNativeCodeDesc desc(1);
2758
2759 /* check arguments */
2760 if (get_prop_check_argc(retval, argc, &desc))
2761 return TRUE;
2762
2763 /* pop the divisor */
2764 G_stk->pop(&val2);
2765
2766 /* convert it to BigNumber */
2767 if (!cvt_to_bignum(vmg_ self, &val2))
2768 {
2769 /* it's not a BigNumber - throw an error */
2770 err_throw(VMERR_BAD_TYPE_BIF);
2771 }
2772
2773 /* get the divisor's extension */
2774 ext2 = get_objid_ext(vmg_ val2.val.obj);
2775
2776 /* push 'self' and the other value to protect against GC */
2777 G_stk->push()->set_obj(self);
2778 G_stk->push(&val2);
2779
2780 /* create a quotient result value, and push it for safekeeping */
2781 quo_ext = compute_init_2op(vmg_ &quo_val, ext_, ext2);
2782 G_stk->push(&quo_val);
2783
2784 /* create a remainder result value, and push it for safekeeping */
2785 rem_ext = compute_init_2op(vmg_ &rem_val, ext_, ext2);
2786 G_stk->push(&rem_val);
2787
2788 /*
2789 * create a list for the return value - it will have two elements:
2790 * the quotient and the remainder
2791 */
2792 retval->set_obj(CVmObjList::create(vmg_ FALSE, 2));
2793 lst = (CVmObjList *)vm_objp(vmg_ retval->val.obj);
2794
2795 /* set the list elements */
2796 lst->cons_set_element(0, &quo_val);
2797 lst->cons_set_element(1, &rem_val);
2798
2799 /* calculate the quotient */
2800 compute_quotient_into(quo_ext, rem_ext, ext_, ext2);
2801
2802 /* remove the GC protection */
2803 G_stk->discard(4);
2804
2805 /* handled */
2806 return TRUE;
2807 }
2808
2809 /*
2810 * property eval - sine
2811 */
2812 int CVmObjBigNum::getp_sin(VMG_ vm_obj_id_t self,
2813 vm_val_t *retval, uint *argc)
2814 {
2815 char *new_ext;
2816 size_t prec = get_prec(ext_);
2817 uint hdl1, hdl2, hdl3, hdl4, hdl5, hdl6, hdl7;
2818 char *ext1, *ext2, *ext3, *ext4, *ext5, *ext6, *ext7;
2819 int neg_result;
2820 const char *pi;
2821
2822 /* check arguments and set up the result */
2823 if (setup_getp_0(vmg_ self, retval, argc, &new_ext))
2824 return TRUE;
2825
2826 /* cache pi */
2827 pi = cache_pi(prec + 3);
2828
2829 /*
2830 * Allocate our temporary registers. We'll use 1 and 2 to calculate
2831 * x^n - we'll start with x^(n-2) in one, and multiply by x^2 to put
2832 * the result in the other. 3 we'll use to store n!. 4 we'll use
2833 * to store the result of x^n/n!, and 5 and 6 we'll swap as the
2834 * master accumulator. 7 we'll use to store x^2.
2835 *
2836 * Allocate the temporary registers with more digits of precision
2837 * than we need in the result, to ensure that accumulated rounding
2838 * errors don't affect the result.
2839 */
2840 alloc_temp_regs(prec + 3, 7,
2841 &ext1, &hdl1, &ext2, &hdl2, &ext3, &hdl3,
2842 &ext4, &hdl4, &ext5, &hdl5, &ext6, &hdl6, &ext7, &hdl7);
2843
2844 /* protect against errors so we definitely free the registers */
2845 err_try
2846 {
2847 char *tmp;
2848
2849 /* copy our initial value to ext1 */
2850 copy_val(ext1, ext_, FALSE);
2851
2852 /*
2853 * Note that sin(-x) = -sin(x). If x < 0, note the negative
2854 * sign and then negate the value so that we calculate sin(x)
2855 * and return the negative of the result.
2856 */
2857 neg_result = get_neg(ext1);
2858 set_neg(ext1, FALSE);
2859
2860 /* calculate 2*pi */
2861 copy_val(ext7, pi, TRUE);
2862 mul_by_long(ext7, 2);
2863
2864 /*
2865 * Because we'll use a Taylor series around 0 to calculate the
2866 * result, we want our value as close to the expansion point (0)
2867 * as possible to speed up convergence of the series.
2868 * Fortunately this is especially easy for sin() because of the
2869 * periodic nature of the function.
2870 *
2871 * First, note that sin(2*pi*i + x) = sin(x) for all integers i,
2872 * so we can reduce the argument mod 2*pi until it's in the
2873 * range 0 <= x < 2*pi (we might have to do this multiple times
2874 * if the number's scale exceeds its precision). Note that we
2875 * already made sure the number is positive.
2876 */
2877 while (compare_abs(ext1, ext7) > 0)
2878 {
2879 /* divide by 2*pi, storing the remainder in r2 */
2880 compute_quotient_into(ext6, ext2, ext1, ext7);
2881
2882 /* swap r2 into r1 for the next round */
2883 tmp = ext1;
2884 ext1 = ext2;
2885 ext2 = tmp;
2886 }
2887
2888 /*
2889 * Next, note that sin(x+pi) = -sin(x). If x > pi, negate the
2890 * result (again if necessary) and reduce the argument by pi.
2891 * This will reduce our range to 0 <= x <= pi.
2892 */
2893 copy_val(ext7, pi, TRUE);
2894 if (compare_abs(ext1, ext7) > 0)
2895 {
2896 /* negate the result */
2897 neg_result = !neg_result;
2898
2899 /* subtract pi from the argument */
2900 compute_abs_diff_into(ext2, ext1, ext7);
2901
2902 /* swap the result into r1 */
2903 tmp = ext1;
2904 ext1 = ext2;
2905 ext2 = tmp;
2906 }
2907
2908 /*
2909 * Use the fact that sin(x + pi) = -sin(x) once again: if x >
2910 * pi/2, subtract pi from x to adjust the range to -pi/2 <= x <=
2911 * pi/2.
2912 */
2913 div_by_long(ext7, 2);
2914 if (compare_abs(ext1, ext7) > 0)
2915 {
2916 /* negate the result */
2917 neg_result = !neg_result;
2918
2919 /* subtract pi from the argument */
2920 copy_val(ext7, pi, TRUE);
2921 compute_abs_diff_into(ext2, ext1, ext7);
2922
2923 /* swap the result into r1 */
2924 tmp = ext1;
2925 ext1 = ext2;
2926 ext2 = tmp;
2927 }
2928
2929 /*
2930 * once again, reduce our range using the sign equivalence -
2931 * this will limit our range to 0 <= x <= pi/2
2932 */
2933 if (get_neg(ext1))
2934 neg_result = !neg_result;
2935 set_neg(ext1, FALSE);
2936
2937 /*
2938 * Next, observe that sin(x+pi/2) = cos(x). If x > pi/4,
2939 * calculate using the cosine series instead of the sine series.
2940 */
2941 copy_val(ext7, pi, TRUE);
2942 div_by_long(ext7, 4);
2943 if (compare_abs(ext1, ext7) > 0)
2944 {
2945 /* calculate pi/2 */
2946 copy_val(ext7, pi, TRUE);
2947 div_by_long(ext7, 2);
2948
2949 /*
2950 * subtract pi/2 - this will give us a value in the range
2951 * -pi/4 <= x <= pi/4
2952 */
2953 compute_abs_diff_into(ext2, ext1, ext7);
2954
2955 /* cos(-x) = cos(x), so we can ignore the sign */
2956 set_neg(ext1, FALSE);
2957
2958 /* swap the result into r1 */
2959 tmp = ext1;
2960 ext1 = ext2;
2961 ext2 = tmp;
2962
2963 /* calculate the cosine series */
2964 calc_cos_series(vmg_ new_ext,
2965 ext1, ext2, ext3, ext4, ext5, ext6, ext7);
2966 }
2967 else
2968 {
2969 /*
2970 * We now have a value in the range 0 <= x <= pi/4, which
2971 * will converge quickly with our Taylor series
2972 */
2973 calc_sin_series(vmg_ new_ext,
2974 ext1, ext2, ext3, ext4, ext5, ext6, ext7);
2975 }
2976
2977 /* negate the result if necessary */
2978 if (neg_result)
2979 set_neg(new_ext, !get_neg(new_ext));
2980
2981 /* normalize the result */
2982 normalize(new_ext);
2983 }
2984 err_finally
2985 {
2986 /* release our temporary registers */
2987 release_temp_regs(7, hdl1, hdl2, hdl3, hdl4, hdl5, hdl6, hdl7);
2988 }
2989 err_end;
2990
2991 /* remove my self-reference */
2992 G_stk->discard();
2993
2994 /* handled */
2995 return TRUE;
2996 }
2997
2998 /*
2999 * property eval - cosine. This works very much the same way as
3000 * getp_sin() - refer to the more extensive comments in that routine for
3001 * more detail on the algorithm.
3002 */
3003 int CVmObjBigNum::getp_cos(VMG_ vm_obj_id_t self,
3004 vm_val_t *retval, uint *argc)
3005 {
3006 char *new_ext;
3007 size_t prec = get_prec(ext_);
3008 uint hdl1, hdl2, hdl3, hdl4, hdl5, hdl6, hdl7;
3009 char *ext1, *ext2, *ext3, *ext4, *ext5, *ext6, *ext7;
3010 int neg_result;
3011 const char *pi;
3012
3013 /* check arguments and set up the result */
3014 if (setup_getp_0(vmg_ self, retval, argc, &new_ext))
3015 return TRUE;
3016
3017 /* cache pi to our working precision */
3018 pi = cache_pi(prec + 3);
3019
3020 /* allocate our temporary registers, as per sin() */
3021 alloc_temp_regs(prec + 3, 7,
3022 &ext1, &hdl1, &ext2, &hdl2, &ext3, &hdl3,
3023 &ext4, &hdl4, &ext5, &hdl5, &ext6, &hdl6, &ext7, &hdl7);
3024
3025 /* protect against errors so we definitely free the registers */
3026 err_try
3027 {
3028 char *tmp;
3029
3030 /* presume the result sign will be correct */
3031 neg_result = FALSE;
3032
3033 /* copy our initial value to ext1 */
3034 copy_val(ext1, ext_, FALSE);
3035
3036 /* note that cos(-x) = cos(x) - if x < 0, use -x */
3037 set_neg(ext1, FALSE);
3038
3039 /* reduce the argument modulo 2*pi */
3040 copy_val(ext7, pi, TRUE);
3041 mul_by_long(ext7, 2);
3042 while (compare_abs(ext1, ext7) > 0)
3043 {
3044 /* divide by 2*pi, storing the remainder in r2 */
3045 compute_quotient_into(ext6, ext2, ext1, ext7);
3046
3047 /* swap r2 into r1 for the next round */
3048 tmp = ext1;
3049 ext1 = ext2;
3050 ext2 = tmp;
3051 }
3052
3053 /*
3054 * Next, note that cos(x+pi) = -cos(x). If x > pi, negate the
3055 * result (again if necessary) and reduce the argument by pi.
3056 * This will reduce our range to 0 <= x <= pi.
3057 */
3058 copy_val(ext7, pi, TRUE);
3059 if (compare_abs(ext1, ext7) > 0)
3060 {
3061 /* negate the result */
3062 neg_result = !neg_result;
3063
3064 /* subtract pi from the argument */
3065 compute_abs_diff_into(ext2, ext1, ext7);
3066
3067 /* swap the result into r1 */
3068 tmp = ext1;
3069 ext1 = ext2;
3070 ext2 = tmp;
3071 }
3072
3073 /*
3074 * Use the fact that cos(x + pi) = -cos(x) once again: if x >
3075 * pi/2, subtract pi from x to adjust the range to -pi/2 <= x <=
3076 * pi/2.
3077 */
3078 div_by_long(ext7, 2);
3079 if (compare_abs(ext1, ext7) > 0)
3080 {
3081 /* negate the result */
3082 neg_result = !neg_result;
3083
3084 /* subtract pi from the argument */
3085 copy_val(ext7, pi, TRUE);
3086 compute_abs_diff_into(ext2, ext1, ext7);
3087
3088 /* swap the result into r1 */
3089 tmp = ext1;
3090 ext1 = ext2;
3091 ext2 = tmp;
3092 }
3093
3094 /*
3095 * once again, reduce our range using the sign equivalence -
3096 * this will limit our range to 0 <= x <= pi/2
3097 */
3098 set_neg(ext1, FALSE);
3099
3100 /*
3101 * Next, observe that cos(x+pi/2) = -sin(x). If x > pi/4,
3102 * calculate using the sine series instead of the cosine series.
3103 */
3104 copy_val(ext7, pi, TRUE);
3105 div_by_long(ext7, 4);
3106 if (compare_abs(ext1, ext7) > 0)
3107 {
3108 /* negate the result */
3109 neg_result = !neg_result;
3110
3111 /* calculate pi/2 */
3112 copy_val(ext7, pi, TRUE);
3113 div_by_long(ext7, 2);
3114
3115 /*
3116 * subtract pi/2 - this will give us a value in the range
3117 * -pi/4 <= x <= pi/4
3118 */
3119 compute_abs_diff_into(ext2, ext1, ext7);
3120
3121 /* sin(-x) = -sin(x) */
3122 if (get_neg(ext1))
3123 neg_result = !neg_result;
3124 set_neg(ext1, FALSE);
3125
3126 /* swap the result into r1 */
3127 tmp = ext1;
3128 ext1 = ext2;
3129 ext2 = tmp;
3130
3131 /* calculate the sine series */
3132 calc_sin_series(vmg_ new_ext,
3133 ext1, ext2, ext3, ext4, ext5, ext6, ext7);
3134 }
3135 else
3136 {
3137 /*
3138 * We now have a value in the range 0 <= x <= pi/4, which
3139 * will converge quickly with our Taylor series
3140 */
3141 calc_cos_series(vmg_ new_ext,
3142 ext1, ext2, ext3, ext4, ext5, ext6, ext7);
3143 }
3144
3145 /* negate the result if necessary */
3146 if (neg_result)
3147 set_neg(new_ext, !get_neg(new_ext));
3148
3149 /* normalize the result */
3150 normalize(new_ext);
3151 }
3152 err_finally
3153 {
3154 /* release our temporary registers */
3155 release_temp_regs(7, hdl1, hdl2, hdl3, hdl4, hdl5, hdl6, hdl7);
3156 }
3157 err_end;
3158
3159 /* remove my self-reference */
3160 G_stk->discard();
3161
3162 /* handled */
3163 return TRUE;
3164 }
3165
3166 /*
3167 * property eval - tangent. We calculate the sine and cosine, then
3168 * compute the quotient to determine the tangent. This routine works
3169 * very much like the sin() and cos() routines; refer to getp_sin() for
3170 * more thorough documentation.
3171 */
3172 int CVmObjBigNum::getp_tan(VMG_ vm_obj_id_t self,
3173 vm_val_t *retval, uint *argc)
3174 {
3175 char *new_ext;
3176 size_t prec = get_prec(ext_);
3177 uint hdl1, hdl2, hdl3, hdl4, hdl5, hdl6, hdl7, hdl8, hdl9;
3178 char *ext1, *ext2, *ext3, *ext4, *ext5, *ext6, *ext7, *ext8, *ext9;
3179 int neg_result;
3180 int invert_result;
3181 const char *pi;
3182
3183 /* check arguments and set up the result */
3184 if (setup_getp_0(vmg_ self, retval, argc, &new_ext))
3185 return TRUE;
3186
3187 /* cache pi to the working precision */
3188 pi = cache_pi(prec + 3);
3189
3190 /*
3191 * Allocate our temporary registers for sin() and cos()
3192 * calculations, plus two extra: one to hold the sine while we're
3193 * calculating the cosine, and the other to hold the cosine result.
3194 *
3195 * (We could make do with fewer registers by copying values around,
3196 * but if the numbers are of very high precision it's much cheaper
3197 * to allocate more registers, since the registers come out of the
3198 * register cache and probably won't require any actual memory
3199 * allocation.)
3200 */
3201 alloc_temp_regs(prec + 3, 9,
3202 &ext1, &hdl1, &ext2, &hdl2, &ext3, &hdl3,
3203 &ext4, &hdl4, &ext5, &hdl5, &ext6, &hdl6,
3204 &ext7, &hdl7, &ext8, &hdl8, &ext9, &hdl9);
3205
3206 /* protect against errors so we definitely free the registers */
3207 err_try
3208 {
3209 char *tmp;
3210
3211 /* presume we won't have to invert our result */
3212 invert_result = FALSE;
3213
3214 /* copy our initial value to ext1 */
3215 copy_val(ext1, ext_, FALSE);
3216
3217 /* note that tan(-x) = -tan(x) - if x < 0, use -x */
3218 neg_result = get_neg(ext1);
3219 set_neg(ext1, FALSE);
3220
3221 /* reduce the argument modulo 2*pi */
3222 copy_val(ext7, pi, TRUE);
3223 mul_by_long(ext7, 2);
3224 while (compare_abs(ext1, ext7) > 0)
3225 {
3226 /* divide by 2*pi, storing the remainder in r2 */
3227 compute_quotient_into(ext6, ext2, ext1, ext7);
3228
3229 /* swap r2 into r1 for the next round */
3230 tmp = ext1;
3231 ext1 = ext2;
3232 ext2 = tmp;
3233 }
3234
3235 /*
3236 * Next, note that tan(x+pi) = tan(x). So, if x > pi, the
3237 * argument by pi. This will reduce our range to 0 <= x <= pi.
3238 */
3239 copy_val(ext7, pi, TRUE);
3240 if (compare_abs(ext1, ext7) > 0)
3241 {
3242 /* subtract pi from the argument */
3243 compute_abs_diff_into(ext2, ext1, ext7);
3244
3245 /* swap the result into r1 */
3246 tmp = ext1;
3247 ext1 = ext2;
3248 ext2 = tmp;
3249 }
3250
3251 /*
3252 * Use the fact that tan(x + pi) = tan(x) once again: if x >
3253 * pi/2, subtract pi from x to adjust the range to -pi/2 <= x <=
3254 * pi/2.
3255 */
3256 div_by_long(ext7, 2);
3257 if (compare_abs(ext1, ext7) > 0)
3258 {
3259 /* subtract pi from the argument */
3260 copy_val(ext7, pi, TRUE);
3261 compute_abs_diff_into(ext2, ext1, ext7);
3262
3263 /* swap the result into r1 */
3264 tmp = ext1;
3265 ext1 = ext2;
3266 ext2 = tmp;
3267 }
3268
3269 /*
3270 * once again, reduce our range using the sign equivalence -
3271 * this will limit our range to 0 <= x <= pi/2
3272 */
3273 if (get_neg(ext1))
3274 neg_result = !neg_result;
3275 set_neg(ext1, FALSE);
3276
3277 /*
3278 * Next, observe that tan(x+pi/2) = 1/tan(x). If x > pi/4,
3279 * invert the result.
3280 */
3281 copy_val(ext7, pi, TRUE);
3282 div_by_long(ext7, 4);
3283 if (compare_abs(ext1, ext7) > 0)
3284 {
3285 /* calculate pi/2 */
3286 copy_val(ext7, pi, TRUE);
3287 div_by_long(ext7, 2);
3288
3289 /* subtract pi/2 to get into range -pi/4 <= x <= pi/4 */
3290 compute_abs_diff_into(ext2, ext1, ext7);
3291
3292 /* sin(-x) = -sin(x) */
3293 if (get_neg(ext1))
3294 neg_result = !neg_result;
3295 set_neg(ext1, FALSE);
3296
3297 /* swap the result into r1 */
3298 tmp = ext1;
3299 ext1 = ext2;
3300 ext2 = tmp;
3301
3302 /* note that we must invert the result */
3303 invert_result = TRUE;
3304 }
3305
3306 /*
3307 * make a copy of our argument value in ext9 for safekeeping
3308 * while we're calculating the sine
3309 */
3310 copy_val(ext9, ext1, FALSE);
3311
3312 /*
3313 * We now have a value in the range 0 <= x <= pi/4, which will
3314 * converge quickly with our Taylor series for sine and cosine.
3315 * This will also ensure that both sin and cos are non-negative,
3316 * so the sign we calculated for the tangent is all that matters
3317 * for the sign.
3318 *
3319 * First, Calculate the sine and store the result in r8.
3320 */
3321 calc_sin_series(vmg_ ext8,
3322 ext1, ext2, ext3, ext4, ext5, ext6, ext7);
3323
3324 /*
3325 * Calculate the cosine and store the result in r1. Note that
3326 * we saved the argument value in ext9 while we were working on
3327 * the sine, so we can now use that value as the argument here.
3328 * ext1 was trashed by the sine calculation, so just use it as
3329 * the output register here.
3330 */
3331 calc_cos_series(vmg_ ext1,
3332 ext9, ext2, ext3, ext4, ext5, ext6, ext7);
3333
3334 /* calculate the quotient sin/cos, or cos/sin if inverted */
3335 if (invert_result)
3336 compute_quotient_into(new_ext, 0, ext1, ext8);
3337 else
3338 compute_quotient_into(new_ext, 0, ext8, ext1);
3339
3340 /* negate the result if necessary */
3341 set_neg(new_ext, neg_result);
3342
3343 /* normalize the result */
3344 normalize(new_ext);
3345 }
3346 err_finally
3347 {
3348 /* release our temporary registers */
3349 release_temp_regs(9, hdl1, hdl2, hdl3, hdl4,
3350 hdl5, hdl6, hdl7, hdl8, hdl9);
3351 }
3352 err_end;
3353
3354 /* remove my self-reference */
3355 G_stk->discard();
3356
3357 /* handled */
3358 return TRUE;
3359 }
3360
3361 /*
3362 * property evaluator - convert degrees to radians
3363 */
3364 int CVmObjBigNum::getp_deg2rad(VMG_ vm_obj_id_t self,
3365 vm_val_t *retval, uint *argc)
3366 {
3367 char *new_ext;
3368 size_t prec = get_prec(ext_);
3369 uint hdl1;
3370 char *ext1;
3371 const char *pi;
3372
3373 /* check arguments and set up the result */
3374 if (setup_getp_0(vmg_ self, retval, argc, &new_ext))
3375 return TRUE;
3376
3377 /* cache pi to our required precision */
3378 pi = cache_pi(prec + 2);
3379
3380 /*
3381 * allocate a temporary register for pi/180 - give it some extra
3382 * precision
3383 */
3384 alloc_temp_regs(prec + 2, 1, &ext1, &hdl1);
3385
3386 /* get pi to our precision */
3387 copy_val(ext1, pi, TRUE);
3388
3389 /* divide pi by 180 */
3390 div_by_long(ext1, 180);
3391
3392 /* multiply our value by pi/180 */
3393 compute_prod_into(new_ext, ext_, ext1);
3394
3395 /* release our temporary registers */
3396 release_temp_regs(1, hdl1);
3397
3398 /* remove my self-reference */
3399 G_stk->discard();
3400
3401 /* handled */
3402 return TRUE;
3403 }
3404
3405 /*
3406 * property evaluator - convert radians to degrees
3407 */
3408 int CVmObjBigNum::getp_rad2deg(VMG_ vm_obj_id_t self,
3409 vm_val_t *retval, uint *argc)
3410 {
3411 char *new_ext;
3412 size_t prec = get_prec(ext_);
3413 uint hdl1;
3414 char *ext1;
3415 const char *pi;
3416
3417 /* check arguments and set up the result */
3418 if (setup_getp_0(vmg_ self, retval, argc, &new_ext))
3419 return TRUE;
3420
3421 /* cache pi to our working precision */
3422 pi = cache_pi(prec + 2);
3423
3424 /* allocate a temporary register for pi/180 */
3425 alloc_temp_regs(prec + 2, 1, &ext1, &hdl1);
3426
3427 /* catch errors so we can be sure to free registers */
3428 err_try
3429 {
3430 /* get pi to our precision */
3431 copy_val(ext1, pi, TRUE);
3432
3433 /* divide pi by 180 */
3434 div_by_long(ext1, 180);
3435
3436 /* divide by pi/180 */
3437 compute_quotient_into(new_ext, 0, ext_, ext1);
3438 }
3439 err_finally
3440 {
3441 /* release our temporary registers */
3442 release_temp_regs(1, hdl1);
3443 }
3444 err_end;
3445
3446 /* remove my self-reference */
3447 G_stk->discard();
3448
3449 /* handled */
3450 return TRUE;
3451 }
3452
3453 /*
3454 * property evaluator - arcsine
3455 */
3456 int CVmObjBigNum::getp_asin(VMG_ vm_obj_id_t self,
3457 vm_val_t *retval, uint *argc)
3458 {
3459 /* calculate and return the arcsine */
3460 return calc_asincos(vmg_ self, retval, argc, FALSE);
3461 }
3462
3463 /*
3464 * property evaluator - arccosine
3465 */
3466 int CVmObjBigNum::getp_acos(VMG_ vm_obj_id_t self,
3467 vm_val_t *retval, uint *argc)
3468 {
3469 /* calculate and return the arcsine */
3470 return calc_asincos(vmg_ self, retval, argc, TRUE);
3471 }
3472
3473 /*
3474 * Common property evaluator routine - arcsine and arccosine. arcsin
3475 * and arccos are related by arccos(x) = pi/2 - arcsin(x). So, to
3476 * calculate an arccos, we can simply calculate the arcsin, then
3477 * subtract the result from pi/2.
3478 */
3479 int CVmObjBigNum::calc_asincos(VMG_ vm_obj_id_t self,
3480 vm_val_t *retval, uint *argc, int is_acos)
3481 {
3482 char *new_ext;
3483
3484 /* check arguments and set up the result */
3485 if (setup_getp_0(vmg_ self, retval, argc, &new_ext))
3486 return TRUE;
3487
3488 /* calculate the arcsin/arccos into the result */
3489 calc_asincos_into(new_ext, ext_, is_acos);
3490
3491 /* remove my self-reference */
3492 G_stk->discard();
3493
3494 /* handled */
3495 return TRUE;
3496 }
3497
3498 /*
3499 * Calculate the arcsine or arccosine into the given result variable
3500 */
3501 void CVmObjBigNum::calc_asincos_into(char *dst, const char *src,
3502 int is_acos)
3503 {
3504 size_t prec = get_prec(dst);
3505 uint hdl1, hdl2, hdl3, hdl4, hdl5;
3506 char *ext1, *ext2, *ext3, *ext4, *ext5;
3507 const char *pi;
3508
3509 /* cache pi to our working precision */
3510 pi = cache_pi(prec + 3);
3511
3512 /*
3513 * allocate our temporary registers - use some extra precision over
3514 * what we need for the result, to reduce the effect of accumulated
3515 * rounding error
3516 */
3517 alloc_temp_regs(prec + 3, 5,
3518 &ext1, &hdl1, &ext2, &hdl2, &ext3, &hdl3,
3519 &ext4, &hdl4, &ext5, &hdl5);
3520
3521 /* catch errors so we release our temp registers */
3522 err_try
3523 {
3524 char *tmp;
3525 static const unsigned char one_over_sqrt2[] =
3526 {
3527 /* precision = 10, scale = 0, flags = 0 */
3528 10, 0, 0, 0, 0,
3529 0x70, 0x71, 0x06, 0x78, 0x14
3530 };
3531 int use_sqrt;
3532 int sqrt_neg;
3533
3534 /* get the initial value of x into our accumulator, r1 */
3535 copy_val(ext1, src, FALSE);
3536
3537 /*
3538 * check to see if the absolute value of the argument is greater
3539 * than 1 - if it is, it's not valid
3540 */
3541 copy_val(ext2, get_one(), FALSE);
3542 if (compare_abs(ext1, ext2) > 0)
3543 err_throw(VMERR_OUT_OF_RANGE);
3544
3545 /* presume we won't need to use the sqrt(1-x^2) method */
3546 use_sqrt = FALSE;
3547
3548 /*
3549 * Check to see if the absolute value of the argument is greater
3550 * than 1/sqrt(2). If it is, the series expansion converges too
3551 * slowly (as slowly as never, if the value is exactly 1). To
3552 * speed things up, in these cases calculate pi/2 -
3553 * asin(sqrt(1-x^2)) instead, which is equivalent but gives us a
3554 * smaller asin() argument for quicker series convergence.
3555 *
3556 * We don't need to compare to 1/sqrt(2) in great precision;
3557 * just use a few digits.
3558 */
3559 copy_val(ext2, (const char *)one_over_sqrt2, TRUE);
3560 if (compare_abs(ext1, ext2) > 0)
3561 {
3562 /* flag that we're using the sqrt method */
3563 use_sqrt = TRUE;
3564
3565 /* note the sign - we'll need to apply this to the result */
3566 sqrt_neg = get_neg(ext1);
3567
3568 /* compute x^2 into r2 */
3569 compute_prod_into(ext2, ext1, ext1);
3570
3571 /* subtract r2 from 1 (by adding -r2 to 1), storing in r4 */
3572 copy_val(ext3, get_one(), FALSE);
3573 make_negative(ext2);
3574 compute_sum_into(ext4, ext3, ext2);
3575
3576 /* compute sqrt(1-x^2) (which is sqrt(r4)) into r1 */
3577 compute_sqrt_into(ext1, ext4);
3578 }
3579
3580 /* compute the arcsine */
3581 ext1 = calc_asin_series(ext1, ext2, ext3, ext4, ext5);
3582
3583 /* if we're using the sqrt method, finish the sqrt calculation */
3584 if (use_sqrt)
3585 {
3586 /* calculate pi/2 */
3587 copy_val(ext2, pi, TRUE);
3588 div_by_long(ext2, 2);
3589
3590 /* compute pi/2 - r1 by negating r1 and adding it */
3591 negate(ext1);
3592 compute_sum_into(ext3, ext2, ext1);
3593
3594 /* negate the result if the original value was negative */
3595 if (sqrt_neg)
3596 negate(ext3);
3597
3598 /* swap the result back into r1 */
3599 tmp = ext1;
3600 ext1 = ext3;
3601 ext3 = tmp;
3602 }
3603
3604 /*
3605 * We now have the arcsine in r1. If we actually wanted the
3606 * arccosine, subtract the arcsine from pi/2 to yield the
3607 * arccosine.
3608 */
3609 if (is_acos)
3610 {
3611 /* get pi/2 into r2 */
3612 copy_val(ext2, pi, TRUE);
3613 div_by_long(ext2, 2);
3614
3615 /* negate r1 to get -asin */
3616 negate(ext1);
3617
3618 /* add -asin to r2 to yield the arccosine in r3 */
3619 compute_sum_into(ext3, ext2, ext1);
3620
3621 /* swap the result back into ext1 */
3622 tmp = ext3;
3623 ext3 = ext1;
3624 ext1 = tmp;
3625 }
3626
3627 /* store the result, rounding if necessary */
3628 copy_val(dst, ext1, TRUE);
3629 }
3630 err_finally
3631 {
3632 /* release our temporary registers */
3633 release_temp_regs(5, hdl1, hdl2, hdl3, hdl4, hdl5);
3634 }
3635 err_end;
3636 }
3637
3638 /*
3639 * Calculate the asin series expansion. This should only be called with
3640 * argument values with absolute value less than 1/sqrt(2), because the
3641 * series converges very slowly for larger values. For operands above
3642 * 1/sqrt(2), the caller should instead compute the equivalent value
3643 *
3644 * +/- (pi/2 - asin(sqrt(1-x^2))).
3645 *
3646 * (+ if x > 0, - if x < 0).
3647 *
3648 * The argument value is in ext1, and we return a pointer to the
3649 * register that contains the result (which will be one of the input
3650 * registers). We use all of the input registers as scratchpads, so
3651 * their values are not retained.
3652 */
3653 char *CVmObjBigNum::calc_asin_series(char *ext1, char *ext2,
3654 char *ext3, char *ext4, char *ext5)
3655 {
3656 ulong n;
3657
3658 /* get the current power of x (1) into the x power register, r2 */
3659 copy_val(ext2, ext1, FALSE);
3660
3661 /*
3662 * compute x^2 into r3 - we'll multiply the previous power by this
3663 * to get the next power (we need x^1, x^3, x^5, etc)
3664 */
3665 compute_prod_into(ext3, ext1, ext1);
3666
3667 /* start at the first term */
3668 n = 1;
3669
3670 /* keep going until we have enough precision in the result */
3671 for (;;)
3672 {
3673 ulong i;
3674 char *tmp;
3675
3676 /* move on to the next term */
3677 n += 2;
3678
3679 /*
3680 * compute the next weirdness factor into r4:
3681 *
3682 * 1*3*5*...*(n-2)
3683 *. -----------------
3684 *. 2*4*6*...*(n-1)*n
3685 */
3686
3687 /* start out with 1 in r4 */
3688 copy_val(ext4, get_one(), FALSE);
3689
3690 /* multiply by odd numbers up to but not including 'n' */
3691 for (i = 3 ; i < n ; i += 2)
3692 mul_by_long(ext4, i);
3693
3694 /*
3695 * Divide by even numbers up to and including n-1. Note that we
3696 * use div_by_long() because it's faster than using a BigNumber
3697 * divisor. div_by_long() has a limit of ULONG_MAX/10 for the
3698 * divisor; we shouldn't have to worry about exceeding that, since
3699 * our maximum precision is 64k digits. The series will converge
3700 * to our maximum precision long before 'i' gets close to
3701 * ULONG_MAX/10. (Even if not, computing billions of series terms
3702 * would take so long that we'd never get there anyway.)
3703 */
3704 for (i = 2 ; i < n ; i += 2)
3705 div_by_long(ext4, i);
3706
3707 /* divide by n */
3708 div_by_long(ext4, n);
3709
3710 /*
3711 * compute the next power of x - multiply our current power of x
3712 * (r2) by x^2 (r3)
3713 */
3714 compute_prod_into(ext5, ext2, ext3);
3715
3716 /* swap r5 into r2 - this new power of x is now current */
3717 tmp = ext5;
3718 ext5 = ext2;
3719 ext2 = tmp;
3720
3721 /*
3722 * multiply the current x power by the current weirdness factor
3723 * - this will yield the current term into r5
3724 */
3725 compute_prod_into(ext5, ext2, ext4);
3726
3727 /*
3728 * if this value is too small to show up in our accumulator,
3729 * we're done
3730 */
3731 if (is_zero(ext5)
3732 || get_exp(ext1) - get_exp(ext5) > (int)get_prec(ext1))
3733 break;
3734
3735 /*
3736 * we can trash the weird factor now - use it as a scratch pad
3737 * for adding the accumulator so far (r1) to this term
3738 */
3739 compute_sum_into(ext4, ext1, ext5);
3740
3741 /* swap the result into r1, since it's the new accumulator */
3742 tmp = ext4;
3743 ext4 = ext1;
3744 ext1 = tmp;
3745 }
3746
3747 /* return the accumulator register */
3748 return ext1;
3749 }
3750
3751 /*
3752 * property evaluator - arctangent
3753 */
3754 int CVmObjBigNum::getp_atan(VMG_ vm_obj_id_t self,
3755 vm_val_t *retval, uint *argc)
3756 {
3757 char *new_ext;
3758 size_t prec = get_prec(ext_);
3759 uint hdl1, hdl2, hdl3, hdl4, hdl5;
3760 char *ext1, *ext2, *ext3, *ext4, *ext5;
3761 const char *pi;
3762
3763 /* check arguments and set up the result */
3764 if (setup_getp_0(vmg_ self, retval, argc, &new_ext))
3765 return TRUE;
3766
3767 /* cache pi to our working precision */
3768 pi = cache_pi(prec + 3);
3769
3770 /* allocate some temporary registers */
3771 alloc_temp_regs(prec + 3, 5,
3772 &ext1, &hdl1, &ext2, &hdl2, &ext3, &hdl3,
3773 &ext4, &hdl4, &ext5, &hdl5);
3774
3775 /* catch errors so we can be sure to free registers */
3776 err_try
3777 {
3778 /*
3779 * If x has absolute value close to 1, either above or below,
3780 * our two series don't converge very rapidly. Happily, we can
3781 * fall back on an alternative in these case by using the
3782 * relation
3783 *
3784 * arctan(x) = (+/-)arccos(1/sqrt(x^2+1))
3785 *
3786 * (The sign of the result is the same as the sign of x.) Since
3787 * we already have routines for arccosine and square root, this
3788 * calculation is easy.
3789 *
3790 * If x doesn't have absolute value close to 1, use the
3791 * appropriate series, since they converge rapidly.
3792 */
3793 if (get_exp(ext_) < -1 || get_exp(ext_) > 2)
3794 {
3795 int term_neg;
3796 ulong n;
3797
3798 /*
3799 * exponent less than -1 -> the number has a small absolute
3800 * value - use the small-x series expansion:
3801 *
3802 * x - x^3/3 + x^5/5 - x^7/7 ...
3803 *
3804 * OR
3805 *
3806 * exponent greater than 2 -> the number has a large
3807 * absolute value, so the large-x series expansion should
3808 * converge quickly:
3809 *
3810 * +/- pi/2 - 1/x + 1/3x^3 - 1/5x^5 ...
3811 *
3812 * (the sign of the leading pi/2 term is positive if x is
3813 * positive, negative if x is negative)
3814 *
3815 * We can commonize these expressions by defining x' = x for
3816 * small x and x' = 1/x for large x, defining C as 0 for
3817 * small x and +/-pi/2 for large X, defining N as +1 for
3818 * small x and -1 for large x, and rewriting the series as:
3819 *
3820 * C + Nx' - Nx'^3/3 + Nx'^5/5 + ...
3821 */
3822
3823 /* check for large or small value */
3824 if (get_exp(ext_) < 0)
3825 {
3826 /* small number - start with zero in the accumulator (r1) */
3827 set_zero(ext1);
3828
3829 /* get the current power of x' into r2 - this is simply x */
3830 copy_val(ext2, ext_, FALSE);
3831
3832 /* the first term (x) is positive */
3833 term_neg = FALSE;
3834 }
3835 else
3836 {
3837 /* large number - start with pi/2 in the accumulator (r1) */
3838 copy_val(ext1, pi, TRUE);
3839 div_by_long(ext1, 2);
3840
3841 /* if x is negative, make that -pi/2 */
3842 set_neg(ext1, get_neg(ext_));
3843
3844 /* get 1/x into r2 - this is our x' term value */
3845 compute_quotient_into(ext2, 0, get_one(), ext_);
3846
3847 /* the first term (1/x) is negative */
3848 term_neg = TRUE;
3849 }
3850
3851 /* start at the first term */
3852 n = 1;
3853
3854 /*
3855 * get x'^2 into r3 - we'll use this to calculate each
3856 * subsequent term (we need x', x'^3, x'^5, etc)
3857 */
3858 compute_prod_into(ext3, ext2, ext2);
3859
3860 /* iterate until we reach the desired precision */
3861 for (;;)
3862 {
3863 char *tmp;
3864
3865 /* copy the current power term from r2 into r4 */
3866 copy_val(ext4, ext2, FALSE);
3867
3868 /*
3869 * divide by the current term constant (we'll never have
3870 * to compute billions of terms to reach our maximum
3871 * possible 64k digits of precision, so 'n' will always be
3872 * way less than the div_by_long limit of ULONG_MAX/10)
3873 */
3874 div_by_long(ext4, n);
3875
3876 /* negate this term if necessary */
3877 if (term_neg)
3878 set_neg(ext4, !get_neg(ext4));
3879
3880 /*
3881 * if we're under the radar on precision, stop looping
3882 * (don't stop on the first term, since the accumulator
3883 * hasn't been fully primed yet)
3884 */
3885 if (n != 1
3886 && (is_zero(ext4)
3887 || (get_exp(ext1) - get_exp(ext4)
3888 > (int)get_prec(ext1))))
3889 break;
3890
3891 /* compute the sum of the accumulator and this term */
3892 compute_sum_into(ext5, ext1, ext4);
3893
3894 /* swap the result back into the accumulator */
3895 tmp = ext1;
3896 ext1 = ext5;
3897 ext5 = tmp;
3898
3899 /*
3900 * move on to the next term - advance n by 2 and swap
3901 * the term sign
3902 */
3903 n += 2;
3904 term_neg = !term_neg;
3905
3906 /*
3907 * compute the next power term - multiply r2 (the latest
3908 * x' power) by r3 (x'^2)
3909 */
3910 compute_prod_into(ext4, ext2, ext3);
3911
3912 /* swap r4 back into r2 - this is now the latest power */
3913 tmp = ext2;
3914 ext2 = ext4;
3915 ext4 = tmp;
3916 }
3917
3918 /* store the result, rounding as needed */
3919 copy_val(new_ext, ext1, TRUE);
3920 }
3921 else
3922 {
3923 /*
3924 * We have a value of x from .01 to 10 - in this range, the
3925 * rewrite using arccosine will give us excellent precision.
3926 */
3927
3928 /* calculate x^2 into r1 */
3929 compute_prod_into(ext1, ext_, ext_);
3930
3931 /* add one (x^2 has to be positive, so don't worry about sign) */
3932 increment_abs(ext1);
3933
3934 /* take the square root and put the result in r2 */
3935 compute_sqrt_into(ext2, ext1);
3936
3937 /* divide that into 1, and put the result back in r1 */
3938 compute_quotient_into(ext1, 0, get_one(), ext2);
3939
3940 /*
3941 * Compute the arccosine of this value - the result is the
3942 * arctangent, so we can store it directly in the output
3943 * register.
3944 */
3945 calc_asincos_into(new_ext, ext1, TRUE);
3946
3947 /* if the input was negative, invert the sign of the result */
3948 if (get_neg(ext_))
3949 negate(new_ext);
3950 }
3951 }
3952 err_finally
3953 {
3954 /* release our temporary registers */
3955 release_temp_regs(5, hdl1, hdl2, hdl3, hdl4, hdl5);
3956 }
3957 err_end;
3958
3959 /* discard the GC protection */
3960 G_stk->discard();
3961
3962 /* handled */
3963 return TRUE;
3964 }
3965
3966 /*
3967 * property evaluator - square root
3968 */
3969 int CVmObjBigNum::getp_sqrt(VMG_ vm_obj_id_t self,
3970 vm_val_t *retval, uint *argc)
3971 {
3972 char *new_ext;
3973
3974 /* check arguments and set up the result */
3975 if (setup_getp_0(vmg_ self, retval, argc, &new_ext))
3976 return TRUE;
3977
3978 /* compute the square root into the result */
3979 compute_sqrt_into(new_ext, ext_);
3980
3981 /* discard the GC protection */
3982 G_stk->discard();
3983
3984 /* handled */
3985 return TRUE;
3986 }
3987
3988 /*
3989 * property evaluator - natural logarithm
3990 */
3991 int CVmObjBigNum::getp_ln(VMG_ vm_obj_id_t self,
3992 vm_val_t *retval, uint *argc)
3993 {
3994 char *new_ext;
3995
3996 /* zero or negative values are not allowed */
3997 if (is_zero(ext_) || get_neg(ext_))
3998 err_throw(VMERR_OUT_OF_RANGE);
3999
4000 /* check arguments and set up the result */
4001 if (setup_getp_0(vmg_ self, retval, argc, &new_ext))
4002 return TRUE;
4003
4004 /* compute the natural logarithm */
4005 compute_ln_into(new_ext, ext_);
4006
4007 /* discard the GC protection */
4008 G_stk->discard();
4009
4010 /* handled */
4011 return TRUE;
4012 }
4013
4014 /*
4015 * property evaluator - exp (exponentiate e, the base of the natural
4016 * logarithm, to the power of this number)
4017 */
4018 int CVmObjBigNum::getp_exp(VMG_ vm_obj_id_t self,
4019 vm_val_t *retval, uint *argc)
4020 {
4021 char *new_ext;
4022
4023 /* check arguments and set up the result */
4024 if (setup_getp_0(vmg_ self, retval, argc, &new_ext))
4025 return TRUE;
4026
4027 /* compute exp(x) */
4028 compute_exp_into(new_ext, ext_);
4029
4030 /* discard the GC protection */
4031 G_stk->discard();
4032
4033 /* handled */
4034 return TRUE;
4035 }
4036
4037 /*
4038 * property evaluator - log10 (base-10 logarithm)
4039 */
4040 int CVmObjBigNum::getp_log10(VMG_ vm_obj_id_t self,
4041 vm_val_t *retval, uint *argc)
4042 {
4043 char *new_ext;
4044 size_t prec = get_prec(ext_);
4045 uint hdl1, hdl2, hdl3;
4046 char *ext1, *ext2, *ext3;
4047 const char *ln10;
4048
4049 /* check arguments and set up the result */
4050 if (setup_getp_0(vmg_ self, retval, argc, &new_ext))
4051 return TRUE;
4052
4053 /* cache ln(10) to the required precision */
4054 ln10 = cache_ln10(prec + 3);
4055
4056 /* allocate some temporary registers */
4057 alloc_temp_regs(prec + 3, 3,
4058 &ext1, &hdl1, &ext2, &hdl2, &ext3, &hdl3);
4059
4060 /* catch errors so we can be sure to free registers */
4061 err_try
4062 {
4063 /* compute the natural logarithm of the number */
4064 compute_ln_into(ext1, ext_);
4065
4066 /* get ln(10), properly rounded */
4067 copy_val(ext2, ln10, TRUE);
4068
4069 /* compute ln(x)/ln(10) to yield log10(x) */
4070 compute_quotient_into(ext3, 0, ext1, ext2);
4071
4072 /* store the result, rounding as needed */
4073 copy_val(new_ext, ext3, TRUE);
4074 }
4075 err_finally
4076 {
4077 /* release our temporary registers */
4078 release_temp_regs(3, hdl1, hdl2, hdl3);
4079 }
4080 err_end;
4081
4082 /* discard the GC protection */
4083 G_stk->discard();
4084
4085 /* handled */
4086 return TRUE;
4087 }
4088
4089 /*
4090 * property evaluator - pow(y) - calculate x^y
4091 */
4092 int CVmObjBigNum::getp_pow(VMG_ vm_obj_id_t self,
4093 vm_val_t *retval, uint *argc)
4094 {
4095 vm_val_t val2;
4096 const char *val2_ext;
4097 char *new_ext;
4098 size_t prec;
4099 uint hdl1, hdl2;
4100 char *ext1, *ext2;
4101
4102 /* check arguments and allocate the result value */
4103 if (setup_getp_1(vmg_ self, retval, argc, &new_ext,
4104 &val2, &val2_ext, FALSE))
4105 return TRUE;
4106
4107 /* use the precision of the result */
4108 prec = get_prec(new_ext);
4109
4110 /*
4111 * Check for a special case: if the number we're exponentiating is
4112 * zero, the result is 0 for any positive exponent, and an error for
4113 * any non-positive exponent (0^0 is undefined, and 0^n where n<0 is
4114 * equivalent to 1/0^n == 1/0, which is a divide-by-zero error).
4115 */
4116 if (is_zero(ext_))
4117 {
4118 /* 0^0 is undefined */
4119 if (is_zero(val2_ext))
4120 err_throw(VMERR_OUT_OF_RANGE);
4121
4122 /* 0^negative is a divide by zero error */
4123 if (get_neg(val2_ext))
4124 err_throw(VMERR_DIVIDE_BY_ZERO);
4125
4126 /* set the result to one, and we're done */
4127 set_zero(new_ext);
4128 goto done;
4129 }
4130
4131 /* allocate some temporary registers */
4132 alloc_temp_regs(prec + 3, 2,
4133 &ext1, &hdl1, &ext2, &hdl2);
4134
4135 /* catch errors so we can be sure to free registers */
4136 err_try
4137 {
4138 int result_neg;
4139
4140 /*
4141 * If a = e^b, then b = ln(a). This means that x^y = e^ln(x^y)
4142 * = e^(y * ln(x)). So, we can compute the result in terms of
4143 * natural logarithm and exponentiation of 'e', for which we
4144 * have primitives we can call.
4145 */
4146
4147 /*
4148 * If x is negative, we can only exponentiate the value to
4149 * integer powers. In this case, we can substitute x' = -x
4150 * (hence x' will be positive), and rewrite the expression as
4151 *
4152 * (-1)^y * (x')^y
4153 *
4154 * We can only calculate (-1)^y for integer values of y, since
4155 * the result is complex if y is not an integer.
4156 */
4157 if (get_neg(ext_))
4158 {
4159 size_t idx;
4160 int units_dig;
4161
4162 /* copy x into r2 */
4163 copy_val(ext2, ext_, FALSE);
4164
4165 /*
4166 * calculate x' = (-x) - since x is negative, this will
4167 * guarantee that x' is positive
4168 */
4169 set_neg(ext2, FALSE);
4170
4171 /*
4172 * make sure y is an integer - start at the first digit
4173 * after the decimal point and check for any non-zero digits
4174 */
4175 idx = (get_exp(val2_ext) < 0 ? 0 : (size_t)get_exp(val2_ext));
4176 for ( ; idx < get_prec(val2_ext) ; ++idx)
4177 {
4178 /* if this digit isn't a zero, it's not an integer */
4179 if (get_dig(val2_ext, idx) != 0)
4180 {
4181 /* y isn't an integer, so we can't calculate (-1)^y */
4182 err_throw(VMERR_OUT_OF_RANGE);
4183 }
4184 }
4185
4186 /* get the first digit to the left of the decimal point */
4187 if (get_exp(val2_ext) <= 0
4188 || (size_t)get_exp(val2_ext) > get_prec(val2_ext))
4189 {
4190 /* the units digit isn't represented - zero is implied */
4191 units_dig = 0;
4192 }
4193 else
4194 {
4195 /* get the digit */
4196 units_dig = get_dig(val2_ext, (size_t)get_exp(val2_ext) - 1);
4197 }
4198
4199 /*
4200 * if the units digit is even, the result will be positive;
4201 * if it's odd, the result will be negative
4202 */
4203 result_neg = ((units_dig & 1) != 0);
4204
4205 /* calculate ln(x') into r1 */
4206 compute_ln_into(ext1, ext2);
4207 }
4208 else
4209 {
4210 /* calculate ln(x) into r1 */
4211 compute_ln_into(ext1, ext_);
4212
4213 /* the result will be positive */
4214 result_neg = FALSE;
4215 }
4216
4217 /* calculate y * ln(x) into r2 */
4218 compute_prod_into(ext2, val2_ext, ext1);
4219
4220 /* calculate exp(r2) = exp(y*ln(x)) = x^y into r1 */
4221 compute_exp_into(ext1, ext2);
4222
4223 /* negate the result if we had a negative x and an odd power */
4224 if (result_neg)
4225 negate(ext1);
4226
4227 /* save the result, rounding as needed */
4228 copy_val(new_ext, ext1, TRUE);
4229 }
4230 err_finally
4231 {
4232 /* release our temporary registers */
4233 release_temp_regs(2, hdl1, hdl2);
4234 }
4235 err_end;
4236
4237 done:
4238 /* discard the GC protection */
4239 G_stk->discard(2);
4240
4241 /* handled */
4242 return TRUE;
4243 }
4244
4245 /*
4246 * property evaluator - sinh
4247 */
4248 int CVmObjBigNum::getp_sinh(VMG_ vm_obj_id_t self,
4249 vm_val_t *retval, uint *argc)
4250 {
4251 /* calculate the hyperbolic sine using the common evaluator */
4252 return calc_sinhcosh(vmg_ self, retval, argc, FALSE, FALSE);
4253 }
4254
4255 /*
4256 * property evaluator - cosh
4257 */
4258 int CVmObjBigNum::getp_cosh(VMG_ vm_obj_id_t self,
4259 vm_val_t *retval, uint *argc)
4260 {
4261 /* calculate the hyperbolic cosine using the common evaluator */
4262 return calc_sinhcosh(vmg_ self, retval, argc, TRUE, FALSE);
4263 }
4264
4265 int CVmObjBigNum::getp_tanh(VMG_ vm_obj_id_t self,
4266 vm_val_t *retval, uint *argc)
4267 {
4268 /* calculate the hyperbolic tangent using the common evaluator */
4269 return calc_sinhcosh(vmg_ self, retval, argc, FALSE, TRUE);
4270 }
4271
4272 /*
4273 * common property evaluator - compute a hyperbolic sine or cosine, or
4274 * do both to calculate a hyperbolic tangent
4275 */
4276 int CVmObjBigNum::calc_sinhcosh(VMG_ vm_obj_id_t self,
4277 vm_val_t *retval, uint *argc,
4278 int is_cosh, int is_tanh)
4279 {
4280 char *new_ext;
4281
4282 /* check arguments and allocate the return value */
4283 if (setup_getp_0(vmg_ self, retval, argc, &new_ext))
4284 return TRUE;
4285
4286 /* calculate the result */
4287 compute_sinhcosh_into(new_ext, ext_, is_cosh, is_tanh);
4288
4289 /* discard the GC protection */
4290 G_stk->discard();
4291
4292 /* handled */
4293 return TRUE;
4294 }
4295
4296 /* ------------------------------------------------------------------------ */
4297 /*
4298 * Compute the fractional part of a number (replacing the value in place).
4299 * This effectively subtracts the integer portion of the number, leaving
4300 * only the fractional portion.
4301 */
4302 void CVmObjBigNum::compute_frac(char *ext)
4303 {
4304 /* get the exponent and precision */
4305 int exp = get_exp(ext);
4306 size_t prec = get_prec(ext);
4307
4308 /* clear out the first n digits, where n is the exponent */
4309 for (size_t idx = 0 ; idx < prec && (int)idx < exp ; ++idx)
4310 set_dig(ext, idx, 0);
4311
4312 /* normalize the result */
4313 normalize(ext);
4314 }
4315
4316 /*
4317 * Get the whole part of a number (replacing the value in place). This
4318 * truncates the number to its integer portion, with no rounding.
4319 */
4320 void CVmObjBigNum::compute_whole(char *ext)
4321 {
4322 /* get the exponent and precision */
4323 int exp = get_exp(ext);
4324 size_t prec = get_prec(ext);
4325
4326 /* check what we have */
4327 if (exp <= 0)
4328 {
4329 /* it's an entirely fractional number - the result is zero */
4330 set_zero(ext);
4331 }
4332 else
4333 {
4334 /* clear digits after the decimal point */
4335 for (size_t idx = (size_t)exp ; idx < prec ; ++idx)
4336 set_dig(ext, idx, 0);
4337
4338 /* normalize the result */
4339 normalize(ext);
4340 }
4341 }
4342
4343
4344 /* ------------------------------------------------------------------------ */
4345 /*
4346 * property evaluator - numType: get the number type information
4347 */
4348
4349 /*
4350 * number types defined in bignum.h - these are part of the public API, so
4351 * they can't be changed
4352 */
4353 #define NumTypeNum 0x0001
4354 #define NumTypeNAN 0x0002
4355 #define NumTypePInf 0x0004
4356 #define NumTypeNInf 0x0008
4357 #define NumTypePZero 0x0010
4358 #define NumTypeNZero 0x0020
4359
4360
4361 int CVmObjBigNum::getp_numType(VMG_ vm_obj_id_t self,
4362 vm_val_t *retval, uint *argc)
4363 {
4364 /* check arguments */
4365 static CVmNativeCodeDesc desc(0);
4366 if (get_prop_check_argc(retval, argc, &desc))
4367 return TRUE;
4368
4369 /* set the appropriate flags */
4370 switch (get_type(ext_))
4371 {
4372 case VMBN_T_NUM:
4373 retval->set_int(NumTypeNum
4374 | (is_zero(ext_)
4375 ? (get_neg(ext_) ? NumTypeNZero : NumTypePZero)
4376 : 0));
4377 break;
4378
4379 case VMBN_T_INF:
4380 retval->set_int(get_neg(ext_) ? NumTypeNInf : NumTypePInf);
4381 break;
4382
4383 case VMBN_T_NAN:
4384 default:
4385 retval->set_int(NumTypeNAN);
4386 break;
4387 }
4388
4389 /* handled */
4390 return TRUE;
4391 }
4392
4393 /* ------------------------------------------------------------------------ */
4394 /*
4395 * Compute a natural logarithm
4396 */
4397 void CVmObjBigNum::compute_ln_into(char *dst, const char *src)
4398 {
4399 uint hdl1, hdl2, hdl3, hdl4, hdl5;
4400 char *ext1, *ext2, *ext3, *ext4, *ext5;
4401 size_t prec = get_prec(dst);
4402 const char *ln10;
4403
4404 /* cache the value of ln(10) */
4405 ln10 = cache_ln10(prec + 3);
4406
4407 /* if the source value is zero, it's an error */
4408 if (is_zero(src))
4409 err_throw(VMERR_OUT_OF_RANGE);
4410
4411 /* allocate some temporary registers */
4412 alloc_temp_regs(prec + 3, 5,
4413 &ext1, &hdl1, &ext2, &hdl2, &ext3, &hdl3,
4414 &ext4, &hdl4, &ext5, &hdl5);
4415
4416 /* catch errors so we can be sure to free registers */
4417 err_try
4418 {
4419 int src_exp;
4420
4421 /*
4422 * Observe that we store our values as x = a*10^b. We can thus
4423 * rewrite ln(x) as ln(a*10^b) = ln(a)+ln(10^b) =
4424 * log(a)+b*ln(10). a is the mantissa, which due to
4425 * normalization is in the range 0.1 <= a < 1.0. Thus, a is an
4426 * ideal argument for the Taylor series. So, we can simply
4427 * compute ln(mantissa), then add it to ln(10)*exponent.
4428 */
4429
4430 /* copy our argument into r1 */
4431 copy_val(ext1, src, FALSE);
4432
4433 /*
4434 * remember the original exponent, and set the exponent of the
4435 * series argument to zero - we'll correct for this later by
4436 * adding the log of the exponent to the series result
4437 */
4438 src_exp = get_exp(ext1);
4439 set_exp(ext1, 0);
4440
4441 /*
4442 * The series expansion is especially efficient for values near
4443 * 1.0. We know the value is now in the range 0.1 <= a < 1.0. So
4444 * if the lead digit of the mantissa is 1, which means the value is
4445 * 0.1 and change, multiply by ten (thus making it 1.0 and change),
4446 * and adjust the exponent accordingly.
4447 */
4448 if (get_dig(ext1, 0) == 1)
4449 {
4450 set_exp(ext1, 1);
4451 --src_exp;
4452 }
4453
4454 /* compute the series expansion */
4455 ext1 = compute_ln_series_into(ext1, ext2, ext3, ext4, ext5);
4456
4457 /* add in the input exponent, properly adjusted */
4458 if (src_exp != 0)
4459 {
4460 /* get ln10 into r2 */
4461 copy_val(ext2, ln10, TRUE);
4462
4463 /* apply the exponent's sign if it's negative */
4464 if (src_exp < 0)
4465 {
4466 set_neg(ext2, TRUE);
4467 src_exp = -src_exp;
4468 }
4469
4470 /* multiply by the exponent */
4471 mul_by_long(ext2, src_exp);
4472
4473 /* add this value to the series expansion value */
4474 compute_sum_into(ext3, ext1, ext2);
4475
4476 /* use this as the result */
4477 ext1 = ext3;
4478 }
4479
4480 /* copy the result, rounding if needed */
4481 copy_val(dst, ext1, TRUE);
4482 }
4483 err_finally
4484 {
4485 /* release our temporary registers */
4486 release_temp_regs(5, hdl1, hdl2, hdl3, hdl4, hdl5);
4487 }
4488 err_end;
4489 }
4490
4491 /*
4492 * Compute the natural log series. The argument value, initially in
4493 * ext1, should be adjusted to a small value before this is called to
4494 * ensure quick series convergence.
4495 */
4496 char *CVmObjBigNum::compute_ln_series_into(char *ext1, char *ext2,
4497 char *ext3, char *ext4,
4498 char *ext5)
4499 {
4500 /* start at the first term of the series */
4501 ulong n = 1;
4502
4503 /* subtract one from r1 to yield (x-1) in r2 */
4504 compute_abs_diff_into(ext2, ext1, get_one());
4505
4506 /* add one to r1 to yield (x+1) */
4507 increment_abs(ext1);
4508
4509 /* compute (x-1)/(x+1) into r3 - this will be our current power */
4510 compute_quotient_into(ext3, 0, ext2, ext1);
4511
4512 /*
4513 * compute ((x-1)/(x+1))^2 into r4 - we'll multiply r3 by this on
4514 * each iteration to produce the next required power, since we only
4515 * need the odd powers
4516 */
4517 compute_prod_into(ext4, ext3, ext3);
4518
4519 /* start out with the first power in our accumulator (r1) */
4520 copy_val(ext1, ext3, FALSE);
4521
4522 /* iterate until we have a good enough answer */
4523 for (;;)
4524 {
4525 /* compute the next power into r2 */
4526 compute_prod_into(ext2, ext3, ext4);
4527
4528 /* copy the result into our current power register, r3 */
4529 copy_val(ext3, ext2, FALSE);
4530
4531 /* advance n */
4532 n += 2;
4533
4534 /*
4535 * divide the power by n (we'll never have to compute billions of
4536 * terms to get our maximum 64k digits of precision, so 'n' will
4537 * always be way less than the div_by_long limit of ULONG_MAX/10)
4538 */
4539 div_by_long(ext2, n);
4540
4541 /* if it's too small to notice, we're done */
4542 if (is_zero(ext2)
4543 || get_exp(ext1) - get_exp(ext2) > (int)get_prec(ext1))
4544 break;
4545
4546 /* compute the sum with our accumulator into r5 */
4547 compute_sum_into(ext5, ext1, ext2);
4548
4549 /* swap r5 and r1 - the new sum is our new accumulator */
4550 char *tmp = ext5;
4551 ext5 = ext1;
4552 ext1 = tmp;
4553 }
4554
4555 /* multiply the result of the series by 2 */
4556 mul_by_long(ext1, 2);
4557
4558 /* return the register containing the result */
4559 return ext1;
4560 }
4561
4562 /*
4563 * Compute e^x, where e is the base of the natural logarithm (2.818...)
4564 */
4565 void CVmObjBigNum::compute_exp_into(char *dst, const char *src)
4566 {
4567 uint hdl1, hdl2, hdl3, hdl4, hdl5, hdl6;
4568 char *ext1, *ext2, *ext3, *ext4, *ext5, *ext6;
4569 size_t prec = get_prec(dst);
4570 const char *ln10;
4571
4572 /* get the constant value of ln10 to the required precision */
4573 ln10 = cache_ln10(prec + 3);
4574
4575 /* allocate temporary registers */
4576 alloc_temp_regs(prec + 3, 6,
4577 &ext1, &hdl1, &ext2, &hdl2, &ext3, &hdl3,
4578 &ext4, &hdl4, &ext5, &hdl5, &ext6, &hdl6);
4579
4580 /* catch errors so we can be sure to free registers */
4581 err_try
4582 {
4583 char *tmp;
4584 ulong n;
4585 ulong n_fact;
4586 int use_int_fact;
4587 long new_exp;
4588 size_t idx;
4589 size_t decpt_idx;
4590 int twos;
4591
4592 /*
4593 * We want to calculate e^x. Observe that a^x = e^(x*ln(x)), so
4594 * 10^x = e^(x*ln(10)). We can rewrite our desired expression
4595 * e^x as
4596 *
4597 * e^[(x/ln(10)) * ln(10)]
4598 *
4599 * which is thus
4600 *
4601 * 10^(x / ln(10))
4602 *
4603 * We store our numbers as a mantissa times 10 raised to an
4604 * integer exponent. Clearly the exponent of 10 in the formula
4605 * above is not always an integer (in fact, it's extremely rare
4606 * that it would be an integer), so we still have more work to
4607 * do. What we must do is obtain an integer exponent. So, let
4608 * us define y = x/ln(10); we can now rewrite the above as
4609 *
4610 * 10^(int(y) + frac(y))
4611 *
4612 * where int(y) is the integer portion of y and frac(y) is the
4613 * fractional portion (y - int(y)). We can rewrite the above as
4614 *
4615 * 10^frac(y) * 10^int(y)
4616 *
4617 * which we can further rewrite as
4618 *
4619 * e^(frac(y)*ln(10)) * 10^int(y)
4620 *
4621 * We haven't made the problem of finding an exponential
4622 * disappear, but we've reduced the argument to a very
4623 * manageable range, which is important because it makes the
4624 * Taylor series converge quickly. Furthermore, it's extremely
4625 * inexpensive to separate out the problem like this, since it
4626 * falls quite naturally out of the representation we use, so it
4627 * doesn't add much overhead to do this preparation work.
4628 */
4629
4630 /* first, calculate x/ln(10) into r1 */
4631 compute_quotient_into(ext1, 0, src, ln10);
4632
4633 /*
4634 * compute the integer portion of x/ln(10) - it has to fit in a
4635 * 16-bit integer, (-32768 to +32767), because this is going to
4636 * be the exponent of the result (or roughly so, anyway)
4637 */
4638 decpt_idx = get_exp(ext1) >= 0 ? (size_t)get_exp(ext1) : 0;
4639 for (new_exp = 0, idx = 0 ; idx < decpt_idx ; ++idx)
4640 {
4641 int dig;
4642
4643 /*
4644 * get this digit if it's represented; if not, it's an
4645 * implied trailing zero
4646 */
4647 dig = (idx < get_prec(ext1) ? get_dig(ext1, idx) : 0);
4648
4649 /* add this digit into the accumulator */
4650 new_exp *= 10;
4651 new_exp += dig;
4652
4653 /*
4654 * Make sure we're still in range. Note that, because our
4655 * representation is 0.dddd*10^x, we need one more factor of
4656 * ten than you'd think here, the adjust of the range from
4657 * the expected -32768..32767
4658 */
4659 if (new_exp > (get_neg(ext1) ? 32769L : 32766L))
4660 err_throw(VMERR_NUM_OVERFLOW);
4661
4662 /*
4663 * zero out this digit, so that when we're done r1 has the
4664 * fractional part only
4665 */
4666 if (idx < get_prec(ext1))
4667 set_dig(ext1, idx, 0);
4668 }
4669
4670 /* negate the exponent value if the source value is negative */
4671 if (get_neg(ext1))
4672 new_exp = -new_exp;
4673
4674 /* normalize the fractional part, which remains in ext1 */
4675 normalize(ext1);
4676
4677 /*
4678 * Multiply it by ln10, storing the result in r3. This is the
4679 * value we'll use with the Taylor series.
4680 */
4681 compute_prod_into(ext3, ext1, ln10);
4682
4683 /*
4684 * While our input value is greater than 0.5, divide it by two to
4685 * make it smaller than 0.5. This will speed up the series
4686 * convergence. When we're done, we'll correct for the divisions
4687 * by squaring the result the same number of times that we halved
4688 * 'x', because e^2x = (e^x)^2.
4689 */
4690 copy_val(ext1, get_one(), FALSE);
4691 div_by_long(ext1, 2);
4692 for (twos = 0 ; compare_abs(ext3, ext1) > 0 ; ++twos)
4693 div_by_long(ext3, 2);
4694
4695 /*
4696 * Start with 1+x in our accumulator (r1). This unrolls the
4697 * trivial first two steps of the loop, where n=0 (term=1) and n=1
4698 * (term=x).
4699 */
4700 copy_val(ext2, get_one(), FALSE);
4701 compute_sum_into(ext1, ext2, ext3);
4702
4703 /* get term n=2 (x^2) into the current-power register (r2) */
4704 compute_prod_into(ext2, ext3, ext3);
4705
4706 /* start with 2 in our factorial register (r4) */
4707 copy_val(ext4, get_one(), FALSE);
4708 mul_by_long(ext4, 2);
4709
4710 /* start at term n=2, n! = 2 */
4711 n = 2;
4712 n_fact = 2;
4713 use_int_fact = TRUE;
4714
4715 /* go until we reach the required precision */
4716 for (;;)
4717 {
4718 /* for efficiency, try integer division */
4719 if (use_int_fact)
4720 {
4721 /*
4722 * we can still fit the factorial in an integer - divide
4723 * by the integer value of n!, since it's a lot faster
4724 */
4725 copy_val(ext5, ext2, FALSE);
4726 div_by_long(ext5, n_fact);
4727
4728 /* calculate the next n! integer, if it'll fit in a long */
4729 if (n_fact > LONG_MAX/10/(n+1))
4730 {
4731 /*
4732 * it'll be too big next time - we'll have to start
4733 * using the full quotient calculation
4734 */
4735 use_int_fact = FALSE;
4736 }
4737 else
4738 {
4739 /* it'll still fit - calculate the next n! */
4740 n_fact *= (n+1);
4741 }
4742 }
4743 else
4744 {
4745 /* compute x^n/n! (r2/r4) into r5 */
4746 compute_quotient_into(ext5, 0, ext2, ext4);
4747 }
4748
4749 /* if we're below the required precision, we're done */
4750 if (is_zero(ext5)
4751 || get_exp(ext1) - get_exp(ext5) > (int)get_prec(ext1))
4752 break;
4753
4754 /* compute the sum of the accumulator and this term into r6 */
4755 compute_sum_into(ext6, ext1, ext5);
4756
4757 /* swap the result into the accumulator */
4758 tmp = ext1;
4759 ext1 = ext6;
4760 ext6 = tmp;
4761
4762 /* on to the next term */
4763 ++n;
4764
4765 /* compute the next factorial value */
4766 mul_by_long(ext4, n);
4767
4768 /* compute the next power of x' into r5 */
4769 compute_prod_into(ext5, ext2, ext3);
4770
4771 /* swap the result into our current-power register (r2) */
4772 tmp = ext2;
4773 ext2 = ext5;
4774 ext5 = tmp;
4775 }
4776
4777 /* square the result as many times as we halved the argument */
4778 for ( ; twos != 0 ; --twos)
4779 {
4780 /* compute the square of r1 into r2 */
4781 compute_prod_into(ext2, ext1, ext1);
4782
4783 /* swap the result back into r1 */
4784 tmp = ext1;
4785 ext1 = ext2;
4786 ext2 = tmp;
4787 }
4788
4789 /*
4790 * set up our 10's exponent value - this is simply 1*10^new_exp,
4791 * which we calculated earlier (which we represent as
4792 * 0.1*10^(new_exp+1)
4793 */
4794 copy_val(ext2, get_one(), FALSE);
4795 set_exp(ext2, (int)(new_exp + 1));
4796
4797 /* multiply by the 10's exponent value */
4798 compute_prod_into(ext3, ext1, ext2);
4799
4800 /* copy the result into the output register, rounding as needed */
4801 copy_val(dst, ext3, TRUE);
4802 }
4803 err_finally
4804 {
4805 /* release our temporary registers */
4806 release_temp_regs(6, hdl1, hdl2, hdl3, hdl4, hdl5, hdl6);
4807 }
4808 err_end;
4809 }
4810
4811 /* ------------------------------------------------------------------------ */
4812 /*
4813 * Compute a hyperbolic sine or cosine
4814 */
4815 void CVmObjBigNum::compute_sinhcosh_into(char *dst, const char *src,
4816 int is_cosh, int is_tanh)
4817 {
4818 size_t prec = get_prec(dst);
4819 uint hdl1, hdl2, hdl3, hdl4;
4820 char *ext1, *ext2, *ext3, *ext4;
4821
4822 /* allocate some temporary registers */
4823 alloc_temp_regs(prec + 3, 4,
4824 &ext1, &hdl1, &ext2, &hdl2, &ext3, &hdl3,
4825 &ext4, &hdl4);
4826
4827 /* catch errors so we can be sure to free registers */
4828 err_try
4829 {
4830 /*
4831 * sinh(x) = (e^x - e^(-x))/2
4832 *
4833 * cosh(x) = (e^x + e^(-x))/2
4834 *
4835 * The two differ only in the sign of the e^(-x) term, so most
4836 * of the calculation is the same for both.
4837 */
4838
4839 /* compute e^x into r1 */
4840 compute_exp_into(ext1, src);
4841
4842 /*
4843 * rather than calculating e^-x separately, simply invert our
4844 * e^x value to yield e^-x (a simple division is much quicker
4845 * than calculating another exponent, which involves an entire
4846 * taylor series expansion)
4847 */
4848 copy_val(ext3, get_one(), FALSE);
4849 compute_quotient_into(ext2, 0, ext3, ext1);
4850
4851 /*
4852 * if we're calculating the tanh, we'll want both the sinh and
4853 * cosh values
4854 */
4855 if (is_tanh)
4856 {
4857 /* add the terms to get the cosh */
4858 compute_sum_into(ext4, ext1, ext2);
4859
4860 /* subtract ext2 to get the sinh */
4861 negate(ext2);
4862 compute_sum_into(ext3, ext1, ext2);
4863
4864 /* tanh is the quotient of sinh/cosh */
4865 compute_quotient_into(ext1, 0, ext3, ext4);
4866
4867 /* our result is in ext1 - set ext3 to point there */
4868 ext3 = ext1;
4869 }
4870 else
4871 {
4872 /*
4873 * if this is sinh, the e^-x term is subtracted; if it's
4874 * cosh, it's added
4875 */
4876 if (!is_cosh)
4877 negate(ext2);
4878
4879 /* compute r1 + r2 into r3 (e^x +/- e^(-x)) */
4880 compute_sum_into(ext3, ext1, ext2);
4881
4882 /* halve the result */
4883 div_by_long(ext3, 2);
4884 }
4885
4886 /* store the result */
4887 copy_val(dst, ext3, TRUE);
4888 }
4889 err_finally
4890 {
4891 /* release our temporary registers */
4892 release_temp_regs(4, hdl1, hdl2, hdl3, hdl4);
4893 }
4894 err_end;
4895 }
4896
4897 /* ------------------------------------------------------------------------ */
4898 /*
4899 * Cache the natural logarithm of 10 to the given precision and return
4900 * the value
4901 */
4902 const char *CVmObjBigNum::cache_ln10(size_t prec)
4903 {
4904 char *ext;
4905 int expanded;
4906 uint hdl1, hdl2, hdl3, hdl4, hdl5;
4907 char *ext1, *ext2, *ext3, *ext4, *ext5;
4908 static const unsigned char ten[] =
4909 {
4910 /* number of digits */
4911 0x01, 0x00,
4912
4913 /* exponent (0.1 * 10^2 = 10) */
4914 0x02, 0x00,
4915
4916 /* flags */
4917 0x00,
4918
4919 /* mantissa */
4920 0x10
4921 };
4922
4923 /*
4924 * round up the precision a bit to ensure that we don't have to
4925 * repeatedly recalculate this value if we're asked for a cluster of
4926 * similar precisions
4927 */
4928 prec = (prec + 7) & ~7;
4929
4930 /* get the ln10 cache register */
4931 ext = S_bignum_cache->get_ln10_reg(calc_alloc(prec), &expanded);
4932
4933 /* if that failed, throw an error */
4934 if (ext == 0)
4935 err_throw(VMERR_OUT_OF_MEMORY);
4936
4937 /*
4938 * if we didn't have to allocate more memory, and the value in the
4939 * register has at least the required precision, return the cached
4940 * value
4941 */
4942 if (!expanded && get_prec(ext) >= prec)
4943 return ext;
4944
4945 /*
4946 * we have reallocated the register, or we just didn't have enough
4947 * precision in the old value - set the new precision
4948 */
4949 set_prec(ext, prec);
4950
4951 /* allocate some temporary registers */
4952 alloc_temp_regs(prec + 3, 5,
4953 &ext1, &hdl1, &ext2, &hdl2, &ext3, &hdl3,
4954 &ext4, &hdl4, &ext5, &hdl5);
4955
4956 /* catch errors so we can be sure to free registers */
4957 err_try
4958 {
4959 /*
4960 * Compute sqrt(10) - 10 is too large for the series to converge,
4961 * but sqrt(10) is good. We'll correct for this later by doubling
4962 * the result of the series expansion, which gives us the correct
4963 * result: ln(a^b) = b*ln(a), and sqrt(x) = x^(1/2), hence
4964 * ln(sqrt(x)) = ln(x)/2, which means that ln(x) = 2*ln(sqrt(x)).
4965 *
4966 * Note that we have to do this the hard way, by explicitly doing
4967 * the ln series rather than just calling compute_ln_into() to get
4968 * the value directly. Why? Because compute_ln_into() needs the
4969 * cached value of ln(10) to do its work. If we called
4970 * compute_ln_into() here, we'd get stuck in a recursion loop.
4971 */
4972
4973 /* compute sqrt(10), for quick series convergence */
4974 copy_val(ext2, (const char *)ten, FALSE);
4975 compute_sqrt_into(ext1, ext2);
4976
4977 /* compute the series expansion */
4978 ext1 = compute_ln_series_into(ext1, ext2, ext3, ext4, ext5);
4979
4980 /* double the result (to adjust for the sqrt) */
4981 mul_by_long(ext1, 2);
4982
4983 /* store the result in the cache */
4984 copy_val(ext, ext1, TRUE);
4985 }
4986 err_finally
4987 {
4988 /* release our temporary registers */
4989 release_temp_regs(5, hdl1, hdl2, hdl3, hdl4, hdl5);
4990 }
4991 err_end;
4992
4993 /* return the register pointer */
4994 return ext;
4995 }
4996
4997 /* ------------------------------------------------------------------------ */
4998 /*
4999 * Cache the natural logarithm of 2 to the given precision and return the
5000 * value
5001 */
5002 const char *CVmObjBigNum::cache_ln2(size_t prec)
5003 {
5004 char *ext;
5005 int expanded;
5006 static const unsigned char two[] = { 0x01, 0x00, 0x01, 0x00, 0x00, 0x20 };
5007
5008 /* round up the precision to minimize recalculations */
5009 prec = (prec + 7) & ~7;
5010
5011 /* get the ln2 cache register */
5012 ext = S_bignum_cache->get_ln2_reg(calc_alloc(prec), &expanded);
5013 if (ext == 0)
5014 err_throw(VMERR_OUT_OF_MEMORY);
5015
5016 /* if we had a cached value with enough precision, return it */
5017 if (!expanded && get_prec(ext) >= prec)
5018 return ext;
5019
5020 /* reallocated - set the new precision and recalculate ln2 */
5021 set_prec(ext, prec);
5022 compute_ln_into(ext, (const char *)two);
5023
5024 /* return the register pointer */
5025 return ext;
5026 }
5027
5028 /* ------------------------------------------------------------------------ */
5029 /*
5030 * Cache pi to the required precision
5031 */
5032 const char *CVmObjBigNum::cache_pi(size_t prec)
5033 {
5034 char *ext;
5035 int expanded;
5036 uint hdl1, hdl2, hdl3, hdl4, hdl5;
5037 char *ext1, *ext2, *ext3, *ext4, *ext5;
5038
5039 /*
5040 * round up the precision a bit to ensure that we don't have to
5041 * repeatedly recalculate this value if we're asked for a cluster of
5042 * similar precisions
5043 */
5044 prec = (prec + 7) & ~7;
5045
5046 /* get the pi cache register */
5047 ext = S_bignum_cache->get_pi_reg(calc_alloc(prec), &expanded);
5048
5049 /* if that failed, throw an error */
5050 if (ext == 0)
5051 err_throw(VMERR_OUT_OF_MEMORY);
5052
5053 /*
5054 * if we didn't have to allocate more memory, and the value in the
5055 * register has at least the required precision, return the cached
5056 * value
5057 */
5058 if (!expanded && get_prec(ext) >= prec)
5059 return ext;
5060
5061 /*
5062 * we have reallocated the register, or we just didn't have enough
5063 * precision in the old value - set the new precision
5064 */
5065 set_prec(ext, prec);
5066
5067 /* allocate some temporary registers */
5068 alloc_temp_regs(prec + 3, 5,
5069 &ext1, &hdl1, &ext2, &hdl2, &ext3, &hdl3,
5070 &ext4, &hdl4, &ext5, &hdl5);
5071
5072 /* catch errors so we can be sure to free registers */
5073 err_try
5074 {
5075 /*
5076 * Compute the arctangent of 1. To do this, rewrite arctan(x) =
5077 * arccos(1/sqrt(1+x^2)), so x=1 gives us arccos(1/sqrt(2)).
5078 *
5079 * Now, arccos(x) = pi/2 - arcsin(x), but this would defeat the
5080 * purpose since we want to calculate pi, thus we don't want to
5081 * depend upon pi in our calculations. Fortunately, arcsin(x) =
5082 * pi/2 - arcsin(sqrt(1-x^2)), hence
5083 *
5084 * pi/2 - arcsin(x) = pi/2 - (pi/2 - arcsin(sqrt(1-x^2)))
5085 *. = arcsin(sqrt(1-x^2))
5086 *
5087 * So, we can rewrite arccos(1/sqrt(2)) as arcsin(sqrt(1/2)).
5088 */
5089
5090 /* compute 1/2 into r2 */
5091 copy_val(ext2, get_one(), FALSE);
5092 div_by_long(ext2, 2);
5093
5094 /* compute sqrt(1/2) into r1 */
5095 compute_sqrt_into(ext1, ext2);
5096
5097 /* calculate the arcsin series for sqrt(1/2) */
5098 ext1 = calc_asin_series(ext1, ext2, ext3, ext4, ext5);
5099
5100 /* multiply the result by 4 */
5101 mul_by_long(ext1, 4);
5102
5103 /* store the result in the cache */
5104 copy_val(ext, ext1, TRUE);
5105 }
5106 err_finally
5107 {
5108 /* release our temporary registers */
5109 release_temp_regs(5, hdl1, hdl2, hdl3, hdl4, hdl5);
5110 }
5111 err_end;
5112
5113 /* return the register pointer */
5114 return ext;
5115 }
5116
5117 /* ------------------------------------------------------------------------ */
5118 /*
5119 * Cache e to the required precision
5120 */
5121 const char *CVmObjBigNum::cache_e(size_t prec)
5122 {
5123 /*
5124 * round up the precision a bit to ensure that we don't have to
5125 * repeatedly recalculate this value if we're asked for a cluster of
5126 * similar precisions
5127 */
5128 prec = (prec + 7) & ~7;
5129
5130 /* get the e cache register */
5131 int expanded;
5132 char *ext = S_bignum_cache->get_e_reg(calc_alloc(prec), &expanded);
5133
5134 /* if that failed, throw an error */
5135 if (ext == 0)
5136 err_throw(VMERR_OUT_OF_MEMORY);
5137
5138 /*
5139 * if we didn't have to allocate more memory, and the value in the
5140 * register has at least the required precision, return the cached
5141 * value
5142 */
5143 if (!expanded && get_prec(ext) >= prec)
5144 return ext;
5145
5146 /*
5147 * we have reallocated the register, or we just didn't have enough
5148 * precision in the old value - set the new precision
5149 */
5150 set_prec(ext, prec);
5151
5152 /* exponentiate the base of the natural logarithm to the power 1 */
5153 compute_exp_into(ext, get_one());
5154
5155 /* return the register pointer */
5156 return ext;
5157 }
5158
5159 /* ------------------------------------------------------------------------ */
5160 /*
5161 * Compute a square root. We use Newton's method (a reliable old method
5162 * for extracting square roots, made better by the fact that, unlike the
5163 * method's inventor, we are fortunate to have an electronic computer to
5164 * carry out the tedious parts of the calculation for us).
5165 */
5166 void CVmObjBigNum::compute_sqrt_into(char *dst, const char *src)
5167 {
5168 uint hdl1, hdl2, hdl3, hdl4;
5169 char *ext1, *ext2, *ext3, *ext4;
5170 size_t dst_prec = get_prec(dst);
5171
5172 /* if the value is negative, it's an error */
5173 if (get_neg(src))
5174 err_throw(VMERR_OUT_OF_RANGE);
5175
5176 /* allocate our scratchpad registers */
5177 alloc_temp_regs(get_prec(dst) + 3, 4,
5178 &ext1, &hdl1, &ext2, &hdl2, &ext3, &hdl3,
5179 &ext4, &hdl4);
5180
5181 /* catch errors so we can free our registers */
5182 err_try
5183 {
5184 /*
5185 * Compute our initial guess. Since our number is represented as
5186 *
5187 * (n * 10^exp),
5188 *
5189 * the square root can be written as
5190 *
5191 * sqrt(n) * sqrt(10^exp) = sqrt(n) * 10^(exp/2)
5192 *
5193 * Approximate sqrt(n) as simply n for our initial guess. This
5194 * will get us to the right order of magnitude plus or minus
5195 * one, so we should converge pretty quickly.
5196 *
5197 * If we have an odd exponent, round up and divide the mantissa
5198 * by 2 - this will be something like 0.456e7, which can be
5199 * written as 4.56e6, whose square root is about 2e3, or .2e4.
5200 *
5201 * If we have an even exponent, multiply the mantissa by 2.
5202 * This will be something like .456e8, whose square root is
5203 * about .67e4.
5204 *
5205 * Note that it's well worth the trouble to make a good initial
5206 * approximation, even with the multiply/divide, because these
5207 * operations with longs are much more efficient than the full
5208 * BigNum divide we'll have to do on each iteration.
5209 */
5210 copy_val(ext1, src, TRUE);
5211 if ((get_exp(ext1) & 1) != 0)
5212 {
5213 /* odd exponent - round up and divide the mantissa by two */
5214 set_exp(ext1, (get_exp(ext1) + 1)/2);
5215 div_by_long(ext1, 2);
5216 }
5217 else
5218 {
5219 /* even exponent - multiply mantissa by two */
5220 set_exp(ext1, get_exp(ext1)/2);
5221 mul_by_long(ext1, 2);
5222 }
5223
5224 /* iterate until we get close enough to the solution */
5225 for (;;)
5226 {
5227 char *tmp;
5228 size_t idx;
5229
5230 /*
5231 * Calculate the next iteration's approximation, noting that r1
5232 * contains the current iteration's value p:
5233 *
5234 * p' = p/2 + src/2p = (p + src/p)/2
5235 *
5236 * Note that if p == 0, we can't compute src/p, so we can't
5237 * iterate any further.
5238 */
5239 if (is_zero(ext1))
5240 break;
5241
5242 /* calculate src/p into r3 */
5243 compute_quotient_into(ext3, 0, src, ext1);
5244
5245 /* compute p + src/p into r4 */
5246 compute_sum_into(ext4, ext1, ext3);
5247
5248 /* compute (p + src/p)/2 into r4 */
5249 div_by_long(ext4, 2);
5250
5251 /*
5252 * check for convergence - if the new value equals the old
5253 * value to the precision requested for the result, we are
5254 * at the limit of our ability to distinguish differences in
5255 * future terms, so we can stop
5256 */
5257 if (get_neg(ext1) == get_neg(ext4)
5258 && get_exp(ext1) == get_exp(ext4))
5259 {
5260 /*
5261 * they're the same sign and magnitude - compare the
5262 * digits to see where they first differ
5263 */
5264 for (idx = 0 ; idx < dst_prec + 1 ; ++idx)
5265 {
5266 /* if they differ here, stop scanning */
5267 if (get_dig(ext1, idx) != get_dig(ext4, idx))
5268 break;
5269 }
5270
5271 /*
5272 * if we didn't find any difference up to the output
5273 * precision plus one digit (for rounding), further
5274 * iteration will be of no value
5275 */
5276 if (idx >= dst_prec + 1)
5277 break;
5278 }
5279
5280 /* swap the new value into r1 for the next round */
5281 tmp = ext1;
5282 ext1 = ext4;
5283 ext4 = tmp;
5284 }
5285
5286 /*
5287 * copy the last iteration's value into the destination,
5288 * rounding as needed
5289 */
5290 copy_val(dst, ext1, TRUE);
5291 }
5292 err_finally
5293 {
5294 /* release our temporary registers */
5295 release_temp_regs(4, hdl1, hdl2, hdl3, hdl4);
5296 }
5297 err_end;
5298 }
5299
5300 /* ------------------------------------------------------------------------ */
5301 /*
5302 * Calculate a Taylor expansion for sin(). The argument is in ext1, and
5303 * we'll store the result in new_ext. ext1 through ext7 are temporary
5304 * registers that we'll overwrite with intermediate values.
5305 *
5306 * Before calling this function, the caller should reduce the value in
5307 * ext1 to the range -pi/4 <= ext1 <= pi/4 to ensure quick convergence
5308 * of the series.
5309 */
5310 void CVmObjBigNum::calc_sin_series(VMG_ char *new_ext, char *ext1,
5311 char *ext2, char *ext3, char *ext4,
5312 char *ext5, char *ext6, char *ext7)
5313 {
5314 ulong n;
5315 int neg_term;
5316 char *tmp;
5317
5318 /* start with 1! (i.e., 1) in r3 */
5319 copy_val(ext3, get_one(), FALSE);
5320
5321 /*
5322 * calculate x^2 into r7 - we need x, x^3, x^5, etc, so we can just
5323 * multiply the last value by x^2 to get the next power we need
5324 */
5325 compute_prod_into(ext7, ext1, ext1);
5326
5327 /* start with x (reduced mod 2pi) in r5 (our accumulator) */
5328 copy_val(ext5, ext1, FALSE);
5329
5330 /* start at term n=1 in our expansion */
5331 n = 1;
5332
5333 /* the first term is positive */
5334 neg_term = FALSE;
5335
5336 /* go until we have a precise enough value */
5337 for (;;)
5338 {
5339 /*
5340 * move on to the next term: multiply r1 by x^2 into r2 to yield
5341 * the next power of x that we require
5342 */
5343 compute_prod_into(ext2, ext1, ext7);
5344
5345 /* swap r1 and r2 - r2 has the next power we need now */
5346 tmp = ext1;
5347 ext1 = ext2;
5348 ext2 = tmp;
5349
5350 /*
5351 * multiply r3 by (n+1)*(n+2) - it currently has n!, so this
5352 * will yield (n+2)!
5353 */
5354 mul_by_long(ext3, (n+1)*(n+2));
5355
5356 /* advance n to the next term */
5357 n += 2;
5358
5359 /* each term swaps signs */
5360 neg_term = !neg_term;
5361
5362 /* divide r1 by r3 to yield the next term in our series in r4 */
5363 compute_quotient_into(ext4, 0, ext1, ext3);
5364
5365 /*
5366 * if this value is too small to count in our accumulator, we're
5367 * done
5368 */
5369 if (is_zero(ext4)
5370 || get_exp(ext5) - get_exp(ext4) > (int)get_prec(ext4))
5371 break;
5372
5373 /*
5374 * invert the sign of the term in r4 if this is a negative term
5375 */
5376 if (neg_term)
5377 set_neg(ext4, !get_neg(ext4));
5378
5379 /* add r4 to our running accumulator in r5, yielding r6 */
5380 compute_sum_into(ext6, ext5, ext4);
5381
5382 /* swap r5 and r6 to put the accumulated value back into r5 */
5383 tmp = ext5;
5384 ext5 = ext6;
5385 ext6 = tmp;
5386 }
5387
5388 /* we're done - store the result, rounding if necessary */
5389 copy_val(new_ext, ext5, TRUE);
5390 }
5391
5392 /*
5393 * Calculate a Taylor expansion for cos(). The argument is in ext1, and
5394 * we'll store the result in new_ext. ext1 through ext7 are temporary
5395 * registers that we'll overwrite with intermediate values.
5396 *
5397 * Before calling this function, the caller should reduce the value in
5398 * ext1 to the range -pi/4 <= ext1 <= pi/4 to ensure quick convergence
5399 * of the series.
5400 */
5401 void CVmObjBigNum::calc_cos_series(VMG_ char *new_ext, char *ext1,
5402 char *ext2, char *ext3, char *ext4,
5403 char *ext5, char *ext6, char *ext7)
5404 {
5405 ulong n;
5406 int neg_term;
5407 char *tmp;
5408
5409 /* start with 2! (i.e., 2) in r3 */
5410 copy_val(ext3, get_one(), FALSE);
5411 set_dig(ext3, 0, 2);
5412
5413 /*
5414 * calculate x^2 into r7 - we need x^2, x^4, x^6, etc, so we can
5415 * just multiply the last value by x^2 to get the next power we need
5416 */
5417 compute_prod_into(ext7, ext1, ext1);
5418
5419 /*
5420 * the first power we need is x^2, so copy it into r1 (our current
5421 * power of x register)
5422 */
5423 copy_val(ext1, ext7, FALSE);
5424
5425 /*
5426 * start with 1 in r5, the accumulator (the first term of the series
5427 * is the constant value 1)
5428 */
5429 copy_val(ext5, get_one(), FALSE);
5430
5431 /*
5432 * start at term n=2 in our expansion (the first term is just the
5433 * constant value 1, so we can start at the second term)
5434 */
5435 n = 2;
5436
5437 /*
5438 * the first term we calculate (i.e., the second term in the actual
5439 * series) is negative
5440 */
5441 neg_term = TRUE;
5442
5443 /* go until we have a precise enough value */
5444 for (;;)
5445 {
5446 /* divide r1 by r3 to yield the next term in our series in r4 */
5447 compute_quotient_into(ext4, 0, ext1, ext3);
5448
5449 /*
5450 * if this value is too small to count in our accumulator, we're
5451 * done
5452 */
5453 if (is_zero(ext4)
5454 || get_exp(ext5) - get_exp(ext4) > (int)get_prec(ext4))
5455 break;
5456
5457 /*
5458 * invert the sign of the term in r4 if this is a negative term
5459 */
5460 if (neg_term)
5461 set_neg(ext4, !get_neg(ext4));
5462
5463 /* add r4 to our running accumulator in r5, yielding r6 */
5464 compute_sum_into(ext6, ext5, ext4);
5465
5466 /* swap r5 and r6 to put the accumulated value back into r5 */
5467 tmp = ext5;
5468 ext5 = ext6;
5469 ext6 = tmp;
5470
5471 /*
5472 * move on to the next term: multiply r1 by x^2 into r2 to yield
5473 * the next power of x that we require
5474 */
5475 compute_prod_into(ext2, ext1, ext7);
5476
5477 /* swap r1 and r2 to put our next required power back in r1 */
5478 tmp = ext1;
5479 ext1 = ext2;
5480 ext2 = tmp;
5481
5482 /*
5483 * multiply r3 by (n+1)*(n+2) - it currently has n!, so this
5484 * will yield (n+2)!
5485 */
5486 mul_by_long(ext3, (n+1)*(n+2));
5487
5488 /* advance n to the next term */
5489 n += 2;
5490
5491 /* each term swaps signs */
5492 neg_term = !neg_term;
5493 }
5494
5495 /* we're done - store the result, rounding if necessary */
5496 copy_val(new_ext, ext5, TRUE);
5497 }
5498
5499 /* ------------------------------------------------------------------------ */
5500 /*
5501 * add a value
5502 */
5503 int CVmObjBigNum::add_val(VMG_ vm_val_t *result,
5504 vm_obj_id_t self, const vm_val_t *val)
5505 {
5506 vm_val_t val2;
5507
5508 /* convert it */
5509 val2 = *val;
5510 if (!cvt_to_bignum(vmg_ self, &val2))
5511 {
5512 /* this type is not convertible to BigNumber, so we can't add it */
5513 err_throw(VMERR_BAD_TYPE_ADD);
5514 }
5515
5516 /* push 'self' and the other value to protect against GC */
5517 G_stk->push()->set_obj(self);
5518 G_stk->push(&val2);
5519
5520 /* compute the sum */
5521 compute_sum(vmg_ result, ext_, get_objid_ext(vmg_ val2.val.obj));
5522
5523 /* discard the GC protection items */
5524 G_stk->discard(2);
5525
5526 /* handled */
5527 return TRUE;
5528 }
5529
5530 /*
5531 * subtract a value
5532 */
5533 int CVmObjBigNum::sub_val(VMG_ vm_val_t *result,
5534 vm_obj_id_t self, const vm_val_t *val)
5535 {
5536 vm_val_t val2;
5537
5538 /* convert it */
5539 val2 = *val;
5540 if (!cvt_to_bignum(vmg_ self, &val2))
5541 {
5542 /* this type is not convertible to BigNumber, so we can't use it */
5543 err_throw(VMERR_BAD_TYPE_SUB);
5544 }
5545
5546 /* push 'self' and the other value to protect against GC */
5547 G_stk->push()->set_obj(self);
5548 G_stk->push(&val2);
5549
5550 /* compute the difference */
5551 compute_diff(vmg_ result, ext_, get_objid_ext(vmg_ val2.val.obj));
5552
5553 /* discard the GC protection items */
5554 G_stk->discard(2);
5555
5556 /* handled */
5557 return TRUE;
5558 }
5559
5560 /*
5561 * multiply a value
5562 */
5563 int CVmObjBigNum::mul_val(VMG_ vm_val_t *result,
5564 vm_obj_id_t self, const vm_val_t *val)
5565 {
5566 vm_val_t val2;
5567
5568 /* convert it */
5569 val2 = *val;
5570 if (!cvt_to_bignum(vmg_ self, &val2))
5571 {
5572 /* this type is not convertible to BigNumber, so we can't add it */
5573 err_throw(VMERR_BAD_TYPE_ADD);
5574 }
5575
5576 /* push 'self' and the other value to protect against GC */
5577 G_stk->push()->set_obj(self);
5578 G_stk->push(&val2);
5579
5580 /* compute the product */
5581 compute_prod(vmg_ result, ext_, get_objid_ext(vmg_ val2.val.obj));
5582
5583 /* discard the GC protection items */
5584 G_stk->discard(2);
5585
5586 /* handled */
5587 return TRUE;
5588 }
5589
5590 /*
5591 * divide a value
5592 */
5593 int CVmObjBigNum::div_val(VMG_ vm_val_t *result,
5594 vm_obj_id_t self, const vm_val_t *val)
5595 {
5596 /* convert it */
5597 vm_val_t val2 = *val;
5598 if (!cvt_to_bignum(vmg_ self, &val2))
5599 {
5600 /* this type is not convertible to BigNumber, so we can't add it */
5601 err_throw(VMERR_BAD_TYPE_ADD);
5602 }
5603
5604 /* push 'self' and the other value to protect against GC */
5605 G_stk->push()->set_obj(self);
5606 G_stk->push(&val2);
5607
5608 /* compute the quotient */
5609 compute_quotient(vmg_ result, ext_, get_objid_ext(vmg_ val2.val.obj));
5610
5611 /* discard the GC protection items */
5612 G_stk->discard(2);
5613
5614 /* handled */
5615 return TRUE;
5616 }
5617
5618 /*
5619 * negate the number
5620 */
5621 int CVmObjBigNum::neg_val(VMG_ vm_val_t *result, vm_obj_id_t self)
5622 {
5623 char *new_ext;
5624 size_t prec = get_prec(ext_);
5625
5626 /*
5627 * If I'm not an ordinary number or an infinity, return myself
5628 * unchanged. Note that we change sign for an infinity, even though
5629 * this might not make a great deal of sense mathematically.
5630 *
5631 * If I'm zero, likewise return myself unchanged. Negative zero is
5632 * still zero.
5633 */
5634 if ((get_type(ext_) != VMBN_T_NUM && get_type(ext_) != VMBN_T_INF)
5635 || is_zero(ext_))
5636 {
5637 /* return myself unchanged */
5638 result->set_obj(self);
5639 return TRUE;
5640 }
5641
5642 /* push a self-reference while we're working */
5643 G_stk->push()->set_obj(self);
5644
5645 /* if I'm an infinity, we don't need any precision in the result */
5646 if (is_infinity(ext_))
5647 prec = 1;
5648
5649 /* create a new number with the same precision as the original */
5650 result->set_obj(create(vmg_ FALSE, prec));
5651 new_ext = get_objid_ext(vmg_ result->val.obj);
5652
5653 /* make a copy in the new object */
5654 memcpy(new_ext, ext_, calc_alloc(prec));
5655
5656 /* reverse the sign */
5657 set_neg(new_ext, !get_neg(new_ext));
5658
5659 /* remove my self-reference */
5660 G_stk->discard();
5661
5662 /* handled */
5663 return TRUE;
5664 }
5665
5666 /* ------------------------------------------------------------------------ */
5667 /*
5668 * check a value for equality
5669 */
5670 int CVmObjBigNum::equals(VMG_ vm_obj_id_t self, const vm_val_t *val,
5671 int /*depth*/) const
5672 {
5673 vm_val_t val2;
5674 int ret;
5675
5676 /* if the other value is a reference to self, we certainly match */
5677 if (val->typ == VM_OBJ && val->val.obj == self)
5678 return TRUE;
5679
5680 /* convert it */
5681 val2 = *val;
5682 if (!cvt_to_bignum(vmg_ self, &val2))
5683 {
5684 /* this type is not convertible to BigNumber - it's not equal */
5685 return FALSE;
5686 }
5687
5688 /* push our values for safekeeping from the garbage collector */
5689 G_stk->push()->set_obj(self);
5690 G_stk->push(&val2);
5691
5692 /* check for equality and return the result */
5693 ret = compute_eq_exact(ext_, get_objid_ext(vmg_ val2.val.obj));
5694
5695 /* discard the stacked values */
5696 G_stk->discard(2);
5697
5698 /* return the result */
5699 return ret;
5700 }
5701
5702 /*
5703 * Hash value calculation
5704 */
5705 uint CVmObjBigNum::calc_hash(VMG_ vm_obj_id_t self, int /*depth*/) const
5706 {
5707 uint i;
5708 uint hash;
5709
5710 /* add up the digits in the number */
5711 for (hash = 0, i = 0 ; i < get_prec(ext_) ; ++i)
5712 {
5713 /* add this digit into the hash so far */
5714 hash += get_dig(ext_, i);
5715 }
5716
5717 /* add in the exponent as well */
5718 hash += (uint)get_exp(ext_);
5719
5720 /* return the combined hash */
5721 return hash;
5722 }
5723
5724 /*
5725 * compare to another value
5726 */
5727 int CVmObjBigNum::compare_to(VMG_ vm_obj_id_t self,
5728 const vm_val_t *val) const
5729 {
5730 vm_val_t val2;
5731
5732 /* convert it */
5733 val2 = *val;
5734 if (!cvt_to_bignum(vmg_ self, &val2))
5735 {
5736 /* this type is not convertible to BigNumber - it's not comparable */
5737 err_throw(VMERR_INVALID_COMPARISON);
5738 }
5739
5740 /* compare the values */
5741 return compare_ext(ext_, get_objid_ext(vmg_ val2.val.obj));
5742 }
5743
5744 /* ------------------------------------------------------------------------ */
5745 /*
5746 * Initialize for a computation involving two operands. Checks the
5747 * operands for non-number values; if either is NAN or INF, allocates a
5748 * result value that is the same non-number type and returns null. If
5749 * both are valid numbers, we'll allocate a result value with precision
5750 * equal to the greater of the precisions of the operands, and we'll
5751 * return a pointer to the new object's extension buffer.
5752 */
5753 char *CVmObjBigNum::compute_init_2op(VMG_ vm_val_t *result,
5754 const char *ext1, const char *ext2)
5755 {
5756 size_t new_prec;
5757 char *new_ext;
5758
5759 /* get the greater precision - this is the precision of the result */
5760 new_prec = get_prec(ext1);
5761 if (get_prec(ext2) > new_prec)
5762 new_prec = get_prec(ext2);
5763
5764 /*
5765 * if either operand is not an ordinary number, we need minimal
5766 * precision to represent the result, since we don't actually need
5767 * to store a number
5768 */
5769 if (is_nan(ext1) || is_nan(ext2))
5770 new_prec = 1;
5771
5772 /* allocate a new object with the required precision */
5773 result->set_obj(create(vmg_ FALSE, new_prec));
5774
5775 /* get the extension buffer */
5776 new_ext = get_objid_ext(vmg_ result->val.obj);
5777
5778 /* check the first value for NAN/INF conditions */
5779 if (get_type(ext1) != VMBN_T_NUM)
5780 {
5781 /* set the result to the same non-number type and sign */
5782 set_type(new_ext, get_type(ext1));
5783 set_neg(new_ext, get_neg(ext1));
5784
5785 /* indicate that no further calculation is necessary */
5786 return 0;
5787 }
5788
5789 /* check the second number for NAN/INF conditions */
5790 if (get_type(ext2) != VMBN_T_NUM)
5791 {
5792 /* set the result to the same non-number type and sign */
5793 set_type(new_ext, get_type(ext2));
5794 set_neg(new_ext, get_neg(ext2));
5795
5796 /* indicate that no further calculation is necessary */
5797 return 0;
5798 }
5799
5800 /* the operands are valid - return the new extension buffer */
5801 return new_ext;
5802 }
5803
5804 /*
5805 * Compute a sum
5806 */
5807 void CVmObjBigNum::compute_sum(VMG_ vm_val_t *result,
5808 const char *ext1, const char *ext2)
5809 {
5810 char *new_ext;
5811
5812 /* allocate our result value */
5813 new_ext = compute_init_2op(vmg_ result, ext1, ext2);
5814
5815 /* we're done if we had a non-number operand */
5816 if (new_ext == 0)
5817 return;
5818
5819 /* compute the sum into the result */
5820 compute_sum_into(new_ext, ext1, ext2);
5821 }
5822
5823 /*
5824 * Compute a difference
5825 */
5826 void CVmObjBigNum::compute_diff(VMG_ vm_val_t *result,
5827 const char *ext1, const char *ext2)
5828 {
5829 /* allocate our result value */
5830 char *new_ext = compute_init_2op(vmg_ result, ext1, ext2);
5831
5832 /* we're done if we had a non-number operand */
5833 if (new_ext == 0)
5834 return;
5835
5836 /* compute the difference into the result object */
5837 compute_diff_into(new_ext, ext1, ext2);
5838 }
5839
5840 /*
5841 * Compute a product
5842 */
5843 void CVmObjBigNum::compute_prod(VMG_ vm_val_t *result,
5844 const char *ext1, const char *ext2)
5845 {
5846 char *new_ext;
5847
5848 /* allocate our result value */
5849 new_ext = compute_init_2op(vmg_ result, ext1, ext2);
5850
5851 /* we're done if we had a non-number operand */
5852 if (new_ext == 0)
5853 return;
5854
5855 /* compute the product */
5856 compute_prod_into(new_ext, ext1, ext2);
5857 }
5858
5859 /*
5860 * Compute a quotient
5861 */
5862 void CVmObjBigNum::compute_quotient(VMG_ vm_val_t *result,
5863 const char *ext1, const char *ext2)
5864 {
5865 char *new_ext;
5866
5867 /* allocate our result value */
5868 new_ext = compute_init_2op(vmg_ result, ext1, ext2);
5869
5870 /* we're done if we had a non-number operand */
5871 if (new_ext == 0)
5872 return;
5873
5874 /* compute the quotient */
5875 compute_quotient_into(new_ext, 0, ext1, ext2);
5876 }
5877
5878 /*
5879 * Determine if two values are equal, rounding the value with greater
5880 * precision to the shorter precision if the two are not of equal
5881 * precision
5882 */
5883 int CVmObjBigNum::compute_eq_round(VMG_ const char *ext1, const char *ext2)
5884 {
5885 size_t prec1 = get_prec(ext1);
5886 size_t prec2 = get_prec(ext2);
5887 const char *shorter;
5888 const char *longer;
5889 char *tmp_ext;
5890 uint tmp_hdl;
5891 int ret;
5892
5893 /*
5894 * allocate a temporary register with a rounded copy of the more
5895 * precise of the values
5896 */
5897 if (prec1 > prec2)
5898 {
5899 /* the first one is longer */
5900 longer = ext1;
5901 shorter = ext2;
5902 }
5903 else if (prec1 < prec2)
5904 {
5905 /* the second one is longer */
5906 longer = ext2;
5907 shorter = ext1;
5908 }
5909 else
5910 {
5911 /* they're the same - do an exact comparison */
5912 return compute_eq_exact(ext1, ext2);
5913 }
5914
5915 /* get a temp register for rounding the longer value */
5916 alloc_temp_regs(get_prec(shorter), 1, &tmp_ext, &tmp_hdl);
5917
5918 /* make a rounded copy */
5919 copy_val(tmp_ext, longer, TRUE);
5920
5921 /* compare the rounded copy of the longer value to the shorter value */
5922 ret = compute_eq_exact(shorter, tmp_ext);
5923
5924 /* release the temporary register */
5925 release_temp_regs(1, tmp_hdl);
5926
5927 /* return the result */
5928 return ret;
5929 }
5930
5931 /*
5932 * Make an exact comparison for equality. If one value is more precise
5933 * than the other, we'll implicitly extend the shorter value to the
5934 * right with trailing zeros.
5935 */
5936 int CVmObjBigNum::compute_eq_exact(const char *ext1, const char *ext2)
5937 {
5938 const char *longer;
5939 size_t min_prec;
5940 size_t max_prec;
5941 size_t prec1;
5942 size_t prec2;
5943 size_t idx;
5944
5945 /*
5946 * if either is not an ordinary number, they are never equal to any
5947 * other value (note that this means INF != INF and NAN != NAN,
5948 * which is reasonable because these values cannot be meaningfully
5949 * compared; one NAN might mean something totally different from
5950 * another, and likewise various infinities are not comparable)
5951 */
5952 if (is_nan(ext1) || is_nan(ext2))
5953 return FALSE;
5954
5955 /* figure out if one is more precise than the other */
5956 prec1 = get_prec(ext1);
5957 prec2 = get_prec(ext2);
5958 if (prec1 > prec2)
5959 {
5960 /* ext1 is longer */
5961 longer = ext1;
5962 max_prec = prec1;
5963 min_prec = prec2;
5964 }
5965 else if (prec2 > prec1)
5966 {
5967 /* ext2 is longer */
5968 longer = ext2;
5969 max_prec = prec2;
5970 min_prec = prec1;
5971 }
5972 else
5973 {
5974 /* they're the same */
5975 longer = 0;
5976 min_prec = max_prec = prec1;
5977 }
5978
5979 /* if the signs aren't the same, the numbers are not equal */
5980 if (get_neg(ext1) != get_neg(ext2))
5981 return FALSE;
5982
5983 /* if the exponents aren't equal, the numbers are not equal */
5984 if (get_exp(ext1) != get_exp(ext2))
5985 return FALSE;
5986
5987 /*
5988 * compare digits up to the smaller precision, then make sure that
5989 * the larger-precision value's digits are all zeros from there out
5990 */
5991 for (idx = 0 ; idx < min_prec ; ++idx)
5992 {
5993 /* if they don't match, return not-equal */
5994 if (get_dig(ext1, idx) != get_dig(ext2, idx))
5995 return FALSE;
5996 }
5997
5998 /* check the longer one to make sure it's all zeros */
5999 if (longer != 0)
6000 {
6001 /* scan the remainder of the longer one */
6002 for ( ; idx < max_prec ; ++idx)
6003 {
6004 /* if this digit is non-zero, it's not a match */
6005 if (get_dig(longer, idx) != 0)
6006 return FALSE;
6007 }
6008 }
6009
6010 /* it's a match */
6011 return TRUE;
6012 }
6013
6014 /* ------------------------------------------------------------------------ */
6015 /*
6016 * Round a value
6017 */
6018 const char *CVmObjBigNum::round_val(VMG_ vm_val_t *new_val, const char *ext,
6019 size_t digits, int always_create)
6020 {
6021 /* presume we need rounding */
6022 int need_round = TRUE;
6023
6024 /*
6025 * if the value is already no longer than the requested precision,
6026 * return the original value; similarly, if we don't have to do any
6027 * rounding to truncate to the requested precision, do not change
6028 * the original object; likewise, don't bother changing anything if
6029 * it's not a number
6030 */
6031 if (get_type(ext) != VMBN_T_NUM || !get_round_dir(ext, digits))
6032 {
6033 if (always_create)
6034 {
6035 /*
6036 * we must create a new object regardless, but it won't need
6037 * rounding
6038 */
6039 need_round = FALSE;
6040 }
6041 else
6042 {
6043 /* return the original value */
6044 new_val->set_nil();
6045 return ext;
6046 }
6047 }
6048
6049 /* allocate a new object with the requested precision */
6050 new_val->set_obj(create(vmg_ FALSE, digits));
6051 char *new_ext = get_objid_ext(vmg_ new_val->val.obj);
6052
6053 /* copy the sign, exponent, and type information */
6054 set_prec(new_ext, digits);
6055 set_neg(new_ext, get_neg(ext));
6056 set_exp(new_ext, get_exp(ext));
6057 set_type(new_ext, get_type(ext));
6058
6059 /*
6060 * if we don't need rounding, just truncate the old mantissa and
6061 * return the result
6062 */
6063 if (!need_round)
6064 {
6065 /* if the new size is smaller, truncate it */
6066 if (digits <= get_prec(ext))
6067 {
6068 /* copy the mantissa up to the requested new size */
6069 memcpy(new_ext + VMBN_MANT, ext + VMBN_MANT, (digits + 1)/2);
6070 }
6071 else
6072 {
6073 /* it's growing - simply copy the old value */
6074 copy_val(new_ext, ext, FALSE);
6075 }
6076
6077 /* return the new value */
6078 return new_ext;
6079 }
6080
6081 /* copy the mantissa up to the requested new precision */
6082 memcpy(new_ext + VMBN_MANT, ext + VMBN_MANT, (digits + 1)/2);
6083
6084 /* round it up */
6085 round_up_abs(new_ext, digits);
6086
6087 /* return the new extension */
6088 return new_ext;
6089 }
6090
6091 /*
6092 * Convert a value to a big number value
6093 */
6094 int CVmObjBigNum::cvt_to_bignum(VMG_ vm_obj_id_t self, vm_val_t *val) const
6095 {
6096 /* if it's an integer, convert it to a BigNum value */
6097 if (val->typ == VM_INT)
6098 {
6099 /*
6100 * put my own value on the stack to ensure I'm not garbage
6101 * collected when creating the new object
6102 */
6103 G_stk->push()->set_obj(self);
6104
6105 /* it's an integer - convert it to a BigNum */
6106 val->set_obj(create(vmg_ FALSE, (long)val->val.intval, 32));
6107
6108 /* done protecting my object reference */
6109 G_stk->discard();
6110 }
6111
6112 /* if it's not a BigNumber object, we can't handle it */
6113 if (val->typ != VM_OBJ
6114 || (vm_objp(vmg_ val->val.obj)->get_metaclass_reg()
6115 != metaclass_reg_))
6116 {
6117 /* indicate that conversion was unsuccessful */
6118 return FALSE;
6119 }
6120
6121 /* successful conversion */
6122 return TRUE;
6123 }
6124