-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFloat.m
More file actions
executable file
·6680 lines (5765 loc) · 155 KB
/
Copy pathFloat.m
File metadata and controls
executable file
·6680 lines (5765 loc) · 155 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ##############################################################
// BigFloat.h
// BigFloat Implementation
//
// Created by Matt Gallagher on Sun Jan 06 2002.
// Copyright © 2002-2003 Matt Gallagher. All rights reserved.
// ##############################################################
#import <Foundation/Foundation.h>
//
// About BigFloat
//
// BigFloat is an arbitrary precision (fixed at compile-time) arbitrary radix floating
// point number format. The entire functionality of the class is implemented in a
// single file for simple inclusion in other projects.
//
// Precision is defined by BF_num_values. It defines how many unsigned longs are
// used to hold the number. Though in reality, only half of each long is used. This
// is so that when you multiply then together, there is room for the result (16 bits
// multiplied by 16 bits requires all 32 bits). If you really wanted to, you could
// change this class so that BF_num_values was chosen at class initialisation time
// (I didn't want to).
//
// Bad design choice: when I created this class, I created it "mutable". What I mean
// is that [object1 add:object:2] changes the value of object1. I thought it was a
// good idea at the time. Having used it, I now realise I was wrong. Sorry. It is really
// annoying when you return a BigFloat and the calling function mucks it up on you.
// Maybe you can learn from my mistake.
//
// Naturally, functionality has been catered to the needs of Magic Number Machine
// a little (especially the limitedString function).
//
// Basic constants defining the precision used by the class
#define BF_num_values 8
#define BF_max_mantissa_length (BF_num_values * 16 + 3)
#define BF_max_exponent_length 32
#if (BF_num_values < 2)
#error BF_num_values must be at least 2
#endif
// Mode for trigonometric operations
typedef enum
{
BF_degrees,
BF_radians,
BF_gradians
} BFTrigMode;
@interface BigFloat : NSObject <NSCopying, NSCoding>
{
@protected
unsigned long bf_array[BF_num_values];
signed int bf_exponent;
unsigned short bf_user_point;
BOOL bf_is_negative;
unsigned short bf_radix;
unsigned short bf_value_precision;
unsigned int bf_value_limit;
unsigned long bf_exponent_precision;
BOOL bf_is_valid;
}
// Constructors
- (id)init;
- (id)initWithMantissa: (unsigned long long)mantissa
exponent: (short)exp
isNegative: (BOOL)flag
radix: (unsigned short)newRadix
userPointAt: (unsigned short)pointLocation;
- (id)initWithInt:(signed int)newValue radix:(unsigned short)newRadix;
- (id)initWithDouble:(double)newValue radix:(unsigned short)newRadix;
- (id)initPiWithRadix:(unsigned short)newRadix;
- (id)initWithCoder:(NSCoder *)coder;
- (void)encodeWithCoder:(NSCoder *)coder;
- (id)copyWithZone:(NSZone*)zone;
+ (BigFloat*)bigFloatWithInt:(signed int)newValue radix:(unsigned short)newRadix;
+ (BigFloat*)bigFloatWithDouble:(double)newValue radix:(unsigned short)newRadix;
+ (BigFloat*)piWithRadix:(unsigned short)newRadix;
// Public Utility Functions
- (BOOL)appendDigit: (short)digit useComplement:(int)complement;
- (void)appendExpDigit:(short)digit;
- (void)deleteDigit;
- (void)deleteExpDigit;
- (void)convertToRadix:(unsigned short)newRadix;
- (void)setUserPoint:(int)pointLocation;
- (int)getUserPoint;
- (int)mantissaLength;
- (unsigned short)radix;
- (BOOL)isValid;
- (BOOL)isNegative;
- (BOOL)hasExponent;
- (BOOL)isZero;
- (NSComparisonResult)compareWith:(BigFloat*)num;
- (BigFloat*)duplicate;
- (void)assign:(BigFloat*)newValue;
- (void)abs;
// Arithmetic Functions
- (void)add:(BigFloat*)num;
- (void)subtract:(BigFloat*)num;
- (void)multiplyBy:(BigFloat*)num;
- (void)divideBy:(BigFloat*)num;
- (void)moduloBy:(BigFloat*)num;
// Extended Mathematics Functions
- (void)powerOfE;
- (void)ln;
- (void)raiseToPower:(BigFloat*)num;
- (void)sqrt;
- (void)inverse;
- (void)logOfBase:(BigFloat *)base;
- (void)sinWithTrigMode:(BFTrigMode)mode inv:(BOOL)useInverse hyp:(BOOL)useHyp;
- (void)cosWithTrigMode:(BFTrigMode)mode inv:(BOOL)useInverse hyp:(BOOL)useHyp;
- (void)tanWithTrigMode:(BFTrigMode)mode inv:(BOOL)useInverse hyp:(BOOL)useHyp;
- (void)factorial;
- (void)sum;
- (void)nPr: (BigFloat*)r;
- (void)nCr: (BigFloat*)r;
- (void)exp3Up;
- (void)exp3Down:(int)displayDigits;
- (void)wholePart;
- (void)fractionalPart;
- (void)bitnot;
- (void)andWith:(BigFloat*)num;
- (void)orWith:(BigFloat*)num;
- (void)xorWith:(BigFloat*)num;
// Conversion Functions
- (double)doubleValue;
- (NSString*)mantissaString;
- (NSString*)exponentString;
- (NSString*)toString;
- (NSString*)toShortString:(int)precision;
- (void)limitedString:(unsigned int)lengthLimit fixedPlaces:(unsigned int)places fillLimit:(BOOL)fill complement:(unsigned int)complement mantissa:(NSString**)mantissaOut exponent:(NSString**)exponentOut;
- (void)debugDisplay;
@end
// #######################################################################
// BigFloat.m
// BigFloat Implementation
//
// Created by Matt Gallagher on Sun Jan 06 2002.
// Copyright © 2002-2003 Matt Gallagher. All rights reserved.
// #######################################################################
#import "BigFloat.h"
//
// About BigFloat
//
// BigFloat is an arbitrary precision (fixed at compile-time) arbitrary radix floating
// point number format. The entire functionality of the class is implemented in a
// single file for simple inclusion in other projects.
//
// Precision is defined by BF_num_values. It defines how many unsigned longs are
// used to hold the number. Though in reality, only half of each long is used. This
// is so that when you multiply then together, there is room for the result (16 bits
// multiplied by 16 bits requires all 32 bits). If you really wanted to, you could
// change this class so that BF_num_values was chosen at class initialisation time
// (I didn't want to).
//
// Bad design choice: when I created this class, I created it "mutable". What I mean
// is that [object1 add:object:2] changes the value of object1. I thought it was a
// good idea at the time. Having used it, I now realise I was wrong. Sorry. It is really
// annoying when you return a BigFloat and the calling function mucks it up on you.
// Maybe you can learn from my mistake.
//
// Naturally, functionality has been catered to the needs of Magic Number Machine
// a little (especially the limitedString function).
//
// An array for cacheing values of pi (initialised to all nil)
static BigFloat* pi_array[36] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
// A string containing the unichar digits 0 to 9 and onwards
static NSString* BF_digits = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// An internally used structure to get the extra information for a number (its "elements")
typedef struct
{
unsigned short bf_radix;
unsigned short bf_value_precision;
unsigned int bf_value_limit;
unsigned long bf_exponent_precision;
signed int bf_exponent;
unsigned short bf_user_point;
BOOL bf_is_negative;
BOOL bf_is_valid;
} BigFloatElements;
#pragma mark
@implementation BigFloat
#pragma mark
#pragma mark ### Inline helper functions ###
//
// BF_ClearValuesArray
//
// Sets every value in a values array to zero
//
inline void
BF_ClearValuesArray(unsigned long *values, unsigned int multiple)
{
int i;
// Set the value to zero
for (i = 0; i < BF_num_values * multiple; i++)
{
values[i] = 0;
}
}
//
// BF_ArrayIsNonZero
//
// Scans a values array looking for any non-zero digits.
//
inline BOOL
BF_ArrayIsNonZero(unsigned long *values, unsigned int multiple)
{
int i;
// Set the value to zero
for (i = 0; i < BF_num_values * multiple; i++)
{
if (values[i] != 0) return YES;
}
return NO;
}
//
// BF_CopyValues
//
// Copies the source values to the destination values.
//
inline void
BF_CopyValues(unsigned long *source, unsigned long *copyArray)
{
int i;
// Do a basic copy of the values into the copyArray
for (i = 0; i < BF_num_values; i++)
{
copyArray[i] = source[i];
}
}
//
// BF_ArrayIsNonZero
//
// Copies the second array into the first. I cannot work out why I have
// both this and the previous function. Oh well.
//
inline void
BF_AssignValues(unsigned long *destination, unsigned long *copyArray)
{
int i;
// overwrite the values with those from the copyArray
for (i = 0; i < BF_num_values; i++)
{
destination[i] = copyArray[i];
}
}
//
// BF_AddToMantissa
//
// Adds a single unsigned long to an array of values.
//
inline void
BF_AddToMantissa(unsigned long *values, unsigned long digit, unsigned long limit, unsigned int multiple)
{
int i;
// Multiply through by the bf_radix and add the digit
for (i = 0; i < BF_num_values * multiple; i++)
{
values[i] += digit;
digit = values[i] / limit;
values[i] %= limit;
}
values[BF_num_values - 1] += digit * limit;
}
//
// BF_AppendDigitToMantissa
//
// Appends a single radix digit to the least significant end of the values array. Space
// is made for the digit by multiplying through by the radix first.
//
inline void
BF_AppendDigitToMantissa(unsigned long *values, unsigned long digit, unsigned short radix, unsigned long limit, unsigned int multiple)
{
int i;
// Multiply through by the bf_radix and add the digit
for (i = 0; i < BF_num_values * multiple; i++)
{
values[i] = (values[i] * radix) + digit;
digit = values[i] / limit;
values[i] = values[i] % limit;
}
values[BF_num_values - 1] += digit * limit;
}
//
// BF_RemoveDigitFromMantissa
//
// Chops a single digit off the end of the values array by dividing through by the radix.
//
inline signed long
BF_RemoveDigitFromMantissa(unsigned long *values, unsigned short radix, unsigned long limit, unsigned int multiple)
{
// Truncate a digit by dividing through by the bf_radix
unsigned long carryBits = 0;
int i;
for (i = (BF_num_values * multiple) - 1; i >= 0; i--)
{
values[i] = values[i] + (carryBits * limit);
carryBits = values[i] % radix;
values[i] = values[i] / radix;
}
return carryBits;
}
//
// BF_RemoveDigitFromMantissaAndFlagEmpty
//
// Chops a single digit off the end of the values array by dividing through by the radix.
// If the result is negative it says so.
//
inline signed long
BF_RemoveDigitFromMantissaAndFlagEmpty(unsigned long *values, unsigned short radix, unsigned long limit, unsigned int multiple, BOOL *isEmpty)
{
// Truncate a digit by dividing through by the bf_radix
unsigned long carryBits = 0;
int i;
BOOL empty = YES;
for (i = (BF_num_values * multiple) - 1; i >= 0; i--)
{
values[i] = values[i] + (carryBits * limit);
carryBits = values[i] % radix;
values[i] = values[i] / radix;
if (values[i] != 0) empty = NO;
}
*isEmpty = empty;
return carryBits;
}
//
// BF_NumDigitsInArray
//
// Counts the number of digits after and including the most significant non-zero digit.
//
inline long
BF_NumDigitsInArray(unsigned long *values, unsigned short radix, unsigned long precision)
{
int digitsInNumber;
int valueNumber;
int digitNumber;
// Trace through the number looking the the most significant non-zero digit
digitsInNumber = BF_num_values * precision;
valueNumber = BF_num_values;
do
{
valueNumber--;
digitNumber = precision - 1;
while
(
(((int)(values[valueNumber] / pow(radix, digitNumber)) % radix) == 0)
&&
digitNumber >= 0
)
{
digitNumber--;
digitsInNumber--;
}
}
while
(
(((int)(values[valueNumber] / pow(radix, digitNumber)) % radix) == 0)
&&
valueNumber > 0
);
return digitsInNumber;
}
//
// BF_NormaliseNumbers
//
// Normalises the mantissas of two floating point numbers so that they can be added
// subtracted or compared.
//
inline void
BF_NormaliseNumbers
(
unsigned long *values,
unsigned long *otherTerm,
BigFloatElements *thisNumElements,
BigFloatElements *otherNumElements
)
{
NSCAssert
(
otherNumElements->bf_radix == thisNumElements->bf_radix,
@"Numbers must have same radix before normalisation"
);
long thisRoundingNum = 0;
long otherRoundingNum = 0;
BOOL thisEmpty = NO;
BOOL otherEmpty = NO;
thisNumElements->bf_exponent -= thisNumElements->bf_user_point;
thisNumElements->bf_user_point = 0;
otherNumElements->bf_exponent -= otherNumElements->bf_user_point;
otherNumElements->bf_user_point = 0;
// Normalise due to otherNum.bf_exponent being greater than bf_exponent
if (otherNumElements->bf_exponent > thisNumElements->bf_exponent)
{
// start by normalising otherNum left
while
(
otherNumElements->bf_exponent > thisNumElements->bf_exponent
&&
otherTerm[BF_num_values - 1] < (otherNumElements->bf_value_limit / otherNumElements->bf_radix)
)
{
BF_AppendDigitToMantissa(otherTerm, 0, otherNumElements->bf_radix, otherNumElements->bf_value_limit, 1);
otherNumElements->bf_exponent--;
}
// then normalise this num to the right
while(otherNumElements->bf_exponent > thisNumElements->bf_exponent && !thisEmpty)
{
thisRoundingNum = BF_RemoveDigitFromMantissaAndFlagEmpty(values, thisNumElements->bf_radix, thisNumElements->bf_value_limit, 1, &thisEmpty);
thisNumElements->bf_exponent++;
}
}
// Normalise due to this bf_exponent being greater than otherNum->bf_exponent
else if (thisNumElements->bf_exponent > otherNumElements->bf_exponent)
{
// start by normalising this num left
while
(
thisNumElements->bf_exponent > otherNumElements->bf_exponent
&&
values[BF_num_values - 1] < (thisNumElements->bf_value_limit / thisNumElements->bf_radix)
)
{
BF_AppendDigitToMantissa(values, 0, thisNumElements->bf_radix, thisNumElements->bf_value_limit, 1);
thisNumElements->bf_exponent--;
}
// then normalise otherNum to the right
while(thisNumElements->bf_exponent > otherNumElements->bf_exponent && !otherEmpty)
{
otherRoundingNum = BF_RemoveDigitFromMantissaAndFlagEmpty(otherTerm, otherNumElements->bf_radix, otherNumElements->bf_value_limit, 1, &otherEmpty);
otherNumElements->bf_exponent++;
}
}
// Apply a round to nearest on any truncated values
if (!otherEmpty && (double)otherRoundingNum >= ((double)thisNumElements->bf_radix / 2.0))
{
BF_AddToMantissa(otherTerm, 1, otherNumElements->bf_value_limit, 1);
}
else if (!thisEmpty && (double)thisRoundingNum >= ((double)thisNumElements->bf_radix / 2.0))
{
BF_AddToMantissa(values, 1, thisNumElements->bf_value_limit, 1);
}
if (thisEmpty && !otherEmpty)
{
thisNumElements->bf_exponent = otherNumElements->bf_exponent;
}
else if (!thisEmpty && otherEmpty)
{
otherNumElements->bf_exponent = thisNumElements->bf_exponent;
}
else if (thisEmpty && otherEmpty)
{
otherNumElements->bf_exponent = 0;
thisNumElements->bf_exponent = 0;
}
}
#pragma mark
#pragma mark ##### Private utility functions #####
//
// calculatePi
//
// Calculate π for the current bf_radix and cache it in the array
// Uses the following iterative method to calculate π (quartically convergeant):
//
// Initial: Set y = sqrt(sqrt(2)-1), c = 0 and p = sqrt(2) - 1
// Loop: Set c = c+1
// Set a = (1-y^4)^(1/4)
// Set y = (1-a)/(1+a)
// Set p = p(1+y)^4-y(1+y+y^2)sqrt(2)4^(c+1)
// π = 1/p
//
// (for those of you playing at home... this is the Ramanujan II formula for π)
//
- (void)calculatePi
{
BigFloat *y;
BigFloat *x;
BigFloat *w;
BigFloat *v;
BigFloat *p;
BigFloat *a;
BigFloat *one;
BigFloat *two;
BigFloat *four;
BigFloat *two_sqrt;
BigFloat *quarter;
BigFloat *prevIteration;
// Setup the initial conditions
one = [[BigFloat alloc] initWithInt: 1 radix: bf_radix];
two = [[BigFloat alloc] initWithInt: 2 radix: bf_radix];
four = [[BigFloat alloc] initWithInt: 4 radix: bf_radix];
two_sqrt = [two copy];
[two_sqrt sqrt];
quarter = [[BigFloat alloc] initWithDouble: 0.25 radix: bf_radix];
p = [two_sqrt copy];
[p subtract: one];
y = [p copy];
[y sqrt];
// Just allocate everything that is initially undefined
a = [one copy];
x = [one copy];
v = [one copy];
w = [one copy];
prevIteration = [one copy];
// Do the loopy bit
while([p compareWith: prevIteration] != NSOrderedSame || ![p isValid])
{
[prevIteration assign: p];
// c = c + 1
// a = (1-y^4)^(1/4)
[x assign: y];
[x multiplyBy: x];
[x multiplyBy: x];
[a assign: one];
[a subtract: x];
[a raiseToPower: quarter];
// y = (1-a)/(1+a)
[y assign: one];
[y subtract: a];
[a add: one];
[y divideBy: a];
// p = p(1+y)^4-y(1+y+y^2)sqrt(2)4^(c+1)
[w assign: y];
[w multiplyBy: w];
[x assign: y];
[x add: one];
[w add: x];
[x multiplyBy: x];
[x multiplyBy: x];
[w multiplyBy: y];
[v multiplyBy: four];
[w multiplyBy: v];
[w multiplyBy: two_sqrt];
if ([x isValid] && [w isValid])
{
[p multiplyBy: x];
[p subtract: w];
}
}
// pi_array is retained permanently (until the program quits)
pi_array[bf_radix] = [[p copy] retain];
[pi_array[bf_radix] inverse];
// Free all the memory
[one release];
[two release];
[four release];
[two_sqrt release];
[quarter release];
[p release];
[y release];
[a release];
[x release];
[v release];
[w release];
[prevIteration release];
}
//
// copyElements
//
// Copies the non value information in a BigFloat
//
- (void)copyElements: (BigFloatElements *)copy
{
// Copy this num's elements into the copy structure
copy->bf_exponent = bf_exponent;
copy->bf_user_point = bf_user_point;
copy->bf_is_negative = bf_is_negative;
copy->bf_radix = bf_radix;
copy->bf_value_precision = bf_value_precision;
copy->bf_value_limit = bf_value_limit;
copy->bf_exponent_precision = bf_exponent_precision;
copy->bf_is_valid = bf_is_valid;
}
//
// assignElements
//
// Sets the non value information in a BigFloat.
//
- (void)assignElements: (BigFloatElements *)copy
{
bf_exponent = copy->bf_exponent;
bf_user_point = copy->bf_user_point;
bf_is_negative = copy->bf_is_negative;
bf_radix = copy->bf_radix;
bf_value_precision = copy->bf_value_precision;
bf_value_limit = copy->bf_value_limit;
bf_exponent_precision = copy->bf_exponent_precision;
bf_is_valid = copy->bf_is_valid;
}
//
// setElements
//
// Allows the elements of a BigFloat to be safely set.
//
- (void)setElements:(unsigned short)radix negative:(BOOL)isNegative exp:(signed short)exponent valid:(BOOL)isValid userPoint:(unsigned short)userPoint
{
// Set everything
bf_exponent = exponent;
bf_is_negative = isNegative;
bf_is_valid = isValid;
// Set the bf_radix (if it is valid)
if (radix < 2 || radix > 36)
radix = 10;
bf_radix = radix;
bf_value_precision = (unsigned long)(log(0xFFFF + 1) / log(radix));
bf_value_limit = (unsigned long)(pow(radix, bf_value_precision));
bf_exponent_precision = (unsigned long)(log(0xFFFF + 1) / log(radix));
// Apply the decimal point
if (userPoint > (bf_value_precision * BF_num_values - 1))
userPoint = (bf_value_precision * BF_num_values - 1);
bf_user_point = userPoint;
}
//
// createUserPoint
//
// Puts a fractional point in a number according to typical expected behaviour.
//
- (void)createUserPoint
{
if ([self isZero])
{
bf_exponent = 0;
bf_user_point = 0;
return;
}
// Extract a user decimal point (because 45.67 is prettier than 4567e-2)
if (bf_exponent < 0)
{
if (-bf_exponent > (bf_value_precision * BF_num_values))
{
bf_exponent += (bf_value_precision * BF_num_values) - 1;
bf_user_point = (bf_value_precision * BF_num_values) - 1;
}
else
{
bf_user_point = -bf_exponent;
bf_exponent = 0;
}
}
// Standard check on the exponent
if (bf_exponent > 0xFFFF || bf_exponent < -0xFFFF)
bf_is_valid = NO;
}
#pragma mark
#pragma mark ##### Constructors #####
//
// init
//
// Hey look, its the default constructor. Bet you've never seen one of these before.
// By default you get a base 10 zero.
//
- (id)init
{
self = [super init];
if (self)
{
BF_ClearValuesArray(bf_array, 1);
[self setElements:10 negative:NO exp:0 valid:YES userPoint:0];
}
return self;
}
//
// initWithMantissa
//
// Allows fairly explicit contruction of a BigFloat.
//
- (id)initWithMantissa: (unsigned long long)mantissa exponent: (short)exp isNegative: (BOOL)flag radix: (unsigned short)newRadix userPointAt: (unsigned short)pointLocation
{
self = [super init];
if (self)
{
[self setElements:newRadix negative:flag exp:exp valid:YES userPoint:pointLocation];
// Set the values
bf_array[0] = (mantissa) % bf_value_limit;
bf_array[1] = (mantissa /= (unsigned long long)bf_value_limit) % bf_value_limit;
#if BF_num_values > 2
bf_array[2] = (mantissa /= (unsigned long long)bf_value_limit) % bf_value_limit;
#if BF_num_values > 3
bf_array[3] = (mantissa /= (unsigned long long)bf_value_limit) % bf_value_limit;
#if BF_num_values > 4
bf_array[4] = (mantissa /= (unsigned long long)bf_value_limit) % bf_value_limit;
#if BF_num_values > 5
bf_array[5] = (mantissa /= (unsigned long long)bf_value_limit) % bf_value_limit;
#endif
#endif
#endif
#endif
}
return self;
}
//
// initWithInt
//
// The most common constructor. Simple and delicious.
//
- (id)initWithInt: (signed int)newValue radix: (unsigned short)newRadix
{
BOOL negative = (newValue < 0);
if (negative) newValue *= -1;
self = [self initWithMantissa: newValue exponent: 0 isNegative: negative radix: newRadix userPointAt: 0];
return self;
}
//
// initWithDouble
//
// Also good but not as fast as initWithInt.
//
- (id)initWithDouble:(double)newValue radix:(unsigned short)newRadix
{
unsigned long long mantissa = 0;
int newExponent;
int i;
int numDigits = 0;
int nextDigit;
double intPart;
double fracPart;
double doubleExponent;
BOOL negative = NO;
int radixValuePrecision;
// Shortcut
if (newValue == 0.0)
return self = [self initWithInt:0 radix:newRadix];
// Determine what the bf_value_precision would be for this bf_radix
radixValuePrecision = (unsigned int)(log(0xFFFF + 1) / log(newRadix));
// Determine the sign
if (newValue < 0)
{
negative = YES;
newValue *= -1;
}
// Get the base bf_radix exponent
doubleExponent = log(newValue) / log(newRadix);
if (doubleExponent < 0)
newExponent = (long)floor(doubleExponent);
else
newExponent = (long)ceil(doubleExponent);
// Remove the exponent from the newValue
newValue /= pow(newRadix, newExponent);
if (*((unsigned long long *)(&newValue)) == 0x8000000000000000ULL)
{
// Generate an NaN and return it
self = [self initWithInt: 0 radix: newRadix];
bf_is_valid = NO;
return self;
}
// Get the digits out one at a time, up to the max precision for a double's mantissa
for (i = 0; i < (int)(radixValuePrecision * sizeof(double)/sizeof(unsigned short) * 0.8); i++)
{
// The next digit should be the only thing left of the decimal point
fracPart = modf(newValue, &intPart);
nextDigit = (int)intPart;
// Only add the digit if it is non-zero
if (nextDigit != 0)
{
// Guard against overflow
if ((0xFFFFFFFFFFFFFFFFULL / newRadix) >= mantissa)
mantissa = mantissa * (unsigned long long)(pow(newRadix, i - numDigits + 1)) + nextDigit;
numDigits = i + 1;
}
// Shift the next digit into place
newValue = fracPart * newRadix;
}
fracPart = modf(newValue, &intPart);
if (newValue > (newRadix / 2) && 0xFFFFFFFFFFFFFFFFULL > mantissa)
{
mantissa++;
while (mantissa % newRadix == 0 && numDigits > 1)
{
mantissa /= newRadix;
numDigits--;
}
}
// Now adjust the exponent into its correct spot
newExponent -= (numDigits - 1);
// Create the big float and return it
self = [self initWithMantissa:mantissa exponent:newExponent isNegative:negative radix:newRadix userPointAt:0];
// Create a user point.
[self createUserPoint];
if (bf_user_point >= numDigits)
{
bf_exponent -= bf_user_point - numDigits + 1;
bf_user_point -= bf_user_point - numDigits + 1;
}
return self;
}
//
// initPiWithRadix
//
// Creates a number and initialises it to π. At one point I was going to have more of these.
// Like a zero, a one and other such numbers. Oh well.
//
- (id)initPiWithRadix:(unsigned short)newRadix
{
self = [self initWithInt:0 radix:newRadix];
if (self != nil)
{
// Make certain that we have a pi for this radix
if (pi_array[newRadix] == nil)
[self calculatePi];
// Don't actually return our private PI (in case the caller messes it up)
[self assign:pi_array[newRadix]];
}
return self;
}
//
// initWithCoder
//
// Part of the NSCoder protocol. Required for copy, paste and other such stuff.
//
- (id)initWithCoder:(NSCoder *)coder
{
unsigned long *values;
int length;
self = [super init];
values = (unsigned long *)[coder decodeBytesForKey:@"BFArray" returnedLength:&length];
NSAssert(length == sizeof(unsigned long)*BF_num_values, @"Value array is wrong length");
BF_AssignValues(bf_array, values);
bf_exponent = [coder decodeIntForKey:@"BFExponent"];
bf_user_point = [coder decodeIntForKey:@"BFUserPoint"];
bf_is_negative = [coder decodeBoolForKey:@"BFIsNegative"];
bf_radix = [coder decodeIntForKey:@"BFRadix"];
bf_value_precision = [coder decodeIntForKey:@"BFValuePrecision"];
bf_value_limit = [coder decodeIntForKey:@"BFValueLimit"];
bf_exponent_precision = [coder decodeIntForKey:@"BFExponentPrecision"];
bf_is_valid = [coder decodeBoolForKey:@"BFIsValid"];
return self;
}
//
// encodeWithCoder
//
// Part of the NSCoder protocol. Required for copy, paste and other such stuff.
//
- (void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeBytes:(const uint8_t *)bf_array length:sizeof(unsigned long)*BF_num_values forKey:@"BFArray"];
[coder encodeInt:bf_exponent forKey:@"BFExponent"];
[coder encodeInt:bf_user_point forKey:@"BFUserPoint"];
[coder encodeBool:bf_is_negative forKey:@"BFIsNegative"];
[coder encodeInt:bf_radix forKey:@"BFRadix"];
[coder encodeInt:bf_value_precision forKey:@"BFValuePrecision"];
[coder encodeInt:bf_value_limit forKey:@"BFValueLimit"];
[coder encodeInt:bf_exponent_precision forKey:@"BFExponentPrecision"];
[coder encodeBool:bf_is_valid forKey:@"BFIsValid"];
}
//
// copyWithZone
//
// Overrides the standard copy method so that it copies things properly.
//
- (id)copyWithZone:(NSZone*)zone
{
BigFloat *copy;
copy = [BigFloat allocWithZone:zone];
BF_CopyValues(self->bf_array, copy->bf_array);
copy->bf_exponent = self->bf_exponent;
copy->bf_user_point = self->bf_user_point;
copy->bf_is_negative = self->bf_is_negative;
copy->bf_radix = self->bf_radix;
copy->bf_value_precision = self->bf_value_precision;
copy->bf_value_limit = self->bf_value_limit;
copy->bf_exponent_precision = self->bf_exponent_precision;
copy->bf_is_valid = self->bf_is_valid;
return copy;
}
//
// bigFloatWithInt
//
// A static method to do this quickly and return an autoreleased BigFloat of an int.
//
+ (BigFloat*)bigFloatWithInt: (signed int)newValue radix: (unsigned short)newRadix
{
return [[[BigFloat alloc] initWithInt:newValue radix:newRadix] autorelease];
}
//
// bigFloatWithDouble
//
// A static method to do this quickly and return an autoreleased BigFloat of a double.
//
+ (BigFloat*)bigFloatWithDouble: (double)newValue radix: (unsigned short)newRadix
{
return [[[BigFloat alloc] initWithDouble:newValue radix:newRadix] autorelease];
}
//
// piWithRadix
//