-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapyfixed.cc
More file actions
1186 lines (1036 loc) · 36.8 KB
/
Copy pathapyfixed.cc
File metadata and controls
1186 lines (1036 loc) · 36.8 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
/*
* APyFixed: Dynamic arbitrary fixed-point data type.
*/
// Python details. These should be included before standard header files:
// https://docs.python.org/3/c-api/intro.html#include-files
#include <Python.h> // PYLONG_BITS_IN_DIGIT, PyLongObject
#include "apyfixed.h"
#include "apyfixed_util.h"
#include "apyfloat.h"
#include "apytypes_common.h"
#include "apytypes_util.h"
#include "ieee754.h"
#include "python_util.h"
// Python object access through Pybind
#include <nanobind/nanobind.h>
namespace nb = nanobind;
// Standard header includes
#include <algorithm> // std::copy, std::max, std::transform, etc...
#include <cassert> // assert()
#include <cmath> // std::isinf, std::isnan
#include <cstddef> // std::size_t
#include <cstring> // std::memcpy
#include <functional> // std::bit_not
#include <initializer_list> // initializer_list
#include <iterator> // std::back_inserter
#include <optional> // std::optional
#include <sstream> // std::stringstream
#include <string> // std::string
#include <vector> // std::vector, std::swap
#include <fmt/format.h>
#include <iostream>
/* ********************************************************************************** *
* * Python constructors * *
* ********************************************************************************** */
APyFixed::APyFixed(
const nb::int_& python_long_int_bit_pattern,
std::optional<int> int_bits,
std::optional<int> frac_bits,
std::optional<int> bits
)
: APyFixed(int_bits, frac_bits, bits)
{
_data = python_long_to_limb_vec(python_long_int_bit_pattern, _data.size());
_overflow_twos_complement(_data.begin(), _data.end(), _bits, _int_bits);
}
/* ********************************************************************************** *
* * More C++ accessible constructors * *
* ********************************************************************************** */
APyFixed::APyFixed(
std::optional<int> int_bits, std::optional<int> frac_bits, std::optional<int> bits
)
: _bits { bits_from_optional(bits, int_bits, frac_bits) }
, _int_bits { int_bits.has_value() ? *int_bits : *bits - *frac_bits }
, _data(bits_to_limbs(_bits), 0)
{
}
APyFixed::APyFixed(int bits, int int_bits)
: _bits { bits }
, _int_bits { int_bits }
, _data(bits_to_limbs(_bits), 0)
{
}
template <typename _IT>
APyFixed::APyFixed(int bits, int int_bits, _IT begin, _IT end)
: APyFixed(bits, int_bits)
{
assert(std::distance(begin, end) >= 0);
// Copy data into resulting vector
std::size_t it_elements = std::distance(begin, end);
std::copy_n(begin, std::min(vector_size(), it_elements), std::begin(_data));
// Two's-complements overflow bits outside of the range
_overflow_twos_complement(std::begin(_data), std::end(_data), _bits, _int_bits);
}
APyFixed::APyFixed(int bits, int int_bits, const std::vector<apy_limb_t>& vec)
: APyFixed(bits, int_bits, std::begin(vec), std::end(vec))
{
}
APyFixed::APyFixed(int bits, int int_bits, std::initializer_list<apy_limb_t> list)
: APyFixed(bits, int_bits, std::begin(list), std::end(list))
{
}
APyFixed::APyFixed(int bits, int int_bits, const ScratchVector<apy_limb_t>& data)
: APyFixed(bits, int_bits, std::begin(data), std::end(data))
{
}
/* ********************************************************************************** *
* * Arithmetic member functions * *
* ********************************************************************************** */
template <class base_op, class ripple_carry_op>
inline APyFixed APyFixed::_apyfixed_base_add_sub(const APyFixed& rhs) const
{
const int res_int_bits = std::max(rhs.int_bits(), int_bits()) + 1;
const int res_frac_bits = std::max(rhs.frac_bits(), frac_bits());
const int res_bits = res_int_bits + res_frac_bits;
APyFixed result(res_bits, res_int_bits);
auto lhs_shift_amount = unsigned(res_frac_bits - frac_bits());
auto rhs_shift_amount = unsigned(res_frac_bits - rhs.frac_bits());
if (unsigned(res_bits) <= APY_LIMB_SIZE_BITS) {
// Result bits fits in a single limb. Use native operation
result._data[0] = base_op {}(
_data[0] << lhs_shift_amount, rhs._data[0] << rhs_shift_amount
);
} else {
// Resulting number of bits is more than one limb. Use ripple-carry operation
ScratchVector<apy_limb_t, 8> operand(bits_to_limbs(res_bits));
_cast_no_quantize_no_overflow(
std::begin(_data),
std::end(_data),
std::begin(result._data),
std::end(result._data),
lhs_shift_amount
);
_cast_no_quantize_no_overflow(
std::begin(rhs._data),
std::end(rhs._data),
std::begin(operand),
std::end(operand),
rhs_shift_amount
);
ripple_carry_op {}(
&result._data[0], // dst
&result._data[0], // src1
&operand[0], // src2
result.vector_size() // limb vector length
);
}
return result;
}
APyFixed APyFixed::operator+(const APyFixed& rhs) const
{
return _apyfixed_base_add_sub<std::plus<>, apy_add_n_functor<>>(rhs);
}
APyFixed APyFixed::operator-(const APyFixed& rhs) const
{
return _apyfixed_base_add_sub<std::minus<>, apy_sub_n_functor<>>(rhs);
}
APyFixed APyFixed::operator*(const APyFixed& rhs) const
{
const int res_int_bits = int_bits() + rhs.int_bits();
const int res_bits = bits() + rhs.bits();
// Result fixed-point number
APyFixed result(res_bits, res_int_bits);
// Single-limb result specialization
if (unsigned(res_bits) <= APY_LIMB_SIZE_BITS) {
result._data[0] = _data[0] * rhs._data[0];
return result; // early exit
}
// Both arguments are single limb, result two limbs
if (unsigned(bits()) <= APY_LIMB_SIZE_BITS
&& unsigned(rhs.bits()) <= APY_LIMB_SIZE_BITS) {
auto [high, low] = long_signed_mult(_data[0], rhs._data[0]);
result._data[1] = high;
result._data[0] = low;
}
// Scratch data:
// * abs_op1: _data.size()
// * abs_op2: rhs._data.size()
// * prod_abs: _data.size() + rhs._data.size()
std::size_t scratch_size = 2 * (_data.size() + rhs._data.size());
ScratchVector<apy_limb_t, 16> scratch(scratch_size);
// Perform the product
fixed_point_product(
std::begin(_data), // src1
std::begin(rhs._data), // src2
std::begin(result._data), // dst
vector_size(), // src1_limbs
rhs.vector_size(), // src2_limbs
bits_to_limbs(res_bits), // dst_limbs
std::begin(scratch), // op1_abs
std::begin(scratch) + _data.size(), // op2_abs
std::begin(scratch) + _data.size() + rhs._data.size() // prod_abs
);
return result;
}
APyFixed APyFixed::operator/(const APyFixed& rhs) const
{
if (rhs.is_zero()) {
PyErr_SetString(PyExc_ZeroDivisionError, "fixed-point division by zero");
throw nb::python_error();
}
const int res_int_bits = 1 + int_bits() + rhs.frac_bits();
const int res_frac_bits = frac_bits() + rhs.int_bits();
const int res_bits = res_int_bits + res_frac_bits;
APyFixed result(res_bits, res_int_bits);
if (unsigned(res_bits) <= APY_LIMB_SIZE_BITS) {
apy_limb_signed_t numerator = _data[0] << rhs.bits();
apy_limb_signed_t denominator = rhs._data[0];
result._data[0] = numerator / denominator;
return result; // early exit
}
// Scratch data (size):
// * abs_num: bits_to_limbs(res_bits)
// * abs_den: rhs._data.size()
std::size_t scratch_size = bits_to_limbs(res_bits) + rhs._data.size();
ScratchVector<apy_limb_t, 16> scratch(scratch_size);
// Absolute value left-shifted numerator
auto abs_num_begin = std::begin(scratch);
auto abs_num_end = abs_num_begin + bits_to_limbs(res_bits);
bool sign_num = limb_vector_abs(_data.begin(), _data.end(), abs_num_begin);
limb_vector_lsl(abs_num_begin, abs_num_end, rhs.bits());
// Absolute value denominator
auto abs_den_begin = abs_num_end;
auto abs_den_end = abs_den_begin + rhs._data.size();
bool sign_den
= limb_vector_abs(rhs._data.cbegin(), rhs._data.cend(), abs_den_begin);
// `apy_unsigned_division` requires the number of *significant* limbs in denominator
std::size_t den_significant_limbs = significant_limbs(abs_den_begin, abs_den_end);
apy_unsigned_division(
&result._data[0], // Quotient
&*abs_num_begin, // Numerator
std::distance(abs_num_begin, abs_num_end), // Numerator limbs
&*abs_den_begin, // Denominator
den_significant_limbs // Denominator significant limbs
);
// Negate result if negative
if (sign_num ^ sign_den) {
limb_vector_negate_inplace(result._data.begin(), result._data.end());
}
return result;
}
APyFixed APyFixed::operator+(const nb::int_& rhs) const
{
return *this + APyFixed::from_integer(rhs, _int_bits, frac_bits());
}
APyFixed APyFixed::operator-(const nb::int_& rhs) const
{
return *this - APyFixed::from_integer(rhs, _int_bits, frac_bits());
}
APyFixed APyFixed::operator*(const nb::int_& rhs) const
{
return *this * APyFixed::from_integer(rhs, _int_bits, frac_bits());
}
APyFixed APyFixed::operator/(const nb::int_& rhs) const
{
return *this / APyFixed::from_integer(rhs, _int_bits, frac_bits());
}
APyFixed APyFixed::operator<<(const int shift_val) const
{
// Left and right shift of data only affects the binary point in the data
APyFixed result = *this;
result._int_bits += shift_val;
return result;
}
APyFixed APyFixed::operator>>(const int shift_val) const
{
// Left and right shift of data only affects the binary point in the data
APyFixed result = *this;
result._int_bits -= shift_val;
return result;
}
APyFixed& APyFixed::operator<<=(const int shift_val)
{
// Left-shift in place
_int_bits += shift_val;
return *this;
}
APyFixed& APyFixed::operator>>=(const int shift_val)
{
// Left-shift in place
_int_bits -= shift_val;
return *this;
}
bool APyFixed::operator==(const APyFixed& rhs) const { return (*this - rhs).is_zero(); }
bool APyFixed::operator!=(const APyFixed& rhs) const { return !(*this == rhs); }
bool APyFixed::operator<(const APyFixed& rhs) const
{
return (*this - rhs).is_negative();
}
bool APyFixed::operator<=(const APyFixed& rhs) const
{
auto diff = *this - rhs;
return diff.is_negative() || diff.is_zero();
}
bool APyFixed::operator>(const APyFixed& rhs) const
{
return (rhs - *this).is_negative();
}
bool APyFixed::operator>=(const APyFixed& rhs) const
{
auto diff = rhs - *this;
return diff.is_negative() || diff.is_zero();
}
bool APyFixed::operator==(const nb::int_& rhs) const
{
const std::vector<apy_limb_t> limb_vec = python_long_to_limb_vec(rhs);
APyFixed rhs_fixed(
APY_LIMB_SIZE_BITS * limb_vec.size(),
APY_LIMB_SIZE_BITS * limb_vec.size(),
limb_vec
);
return *this == rhs_fixed;
}
bool APyFixed::operator!=(const nb::int_& rhs) const
{
const std::vector<apy_limb_t> limb_vec = python_long_to_limb_vec(rhs);
APyFixed rhs_fixed(
APY_LIMB_SIZE_BITS * limb_vec.size(),
APY_LIMB_SIZE_BITS * limb_vec.size(),
limb_vec
);
return *this != rhs_fixed;
}
bool APyFixed::operator<(const nb::int_& rhs) const
{
const std::vector<apy_limb_t> limb_vec = python_long_to_limb_vec(rhs);
APyFixed rhs_fixed(
APY_LIMB_SIZE_BITS * limb_vec.size(),
APY_LIMB_SIZE_BITS * limb_vec.size(),
limb_vec
);
return *this < rhs_fixed;
}
bool APyFixed::operator<=(const nb::int_& rhs) const
{
const std::vector<apy_limb_t> limb_vec = python_long_to_limb_vec(rhs);
APyFixed rhs_fixed(
APY_LIMB_SIZE_BITS * limb_vec.size(),
APY_LIMB_SIZE_BITS * limb_vec.size(),
limb_vec
);
return *this <= rhs_fixed;
}
bool APyFixed::operator>(const nb::int_& rhs) const
{
const std::vector<apy_limb_t> limb_vec = python_long_to_limb_vec(rhs);
APyFixed rhs_fixed(
APY_LIMB_SIZE_BITS * limb_vec.size(),
APY_LIMB_SIZE_BITS * limb_vec.size(),
limb_vec
);
return *this > rhs_fixed;
}
bool APyFixed::operator>=(const nb::int_& rhs) const
{
const std::vector<apy_limb_t> limb_vec = python_long_to_limb_vec(rhs);
APyFixed rhs_fixed(
APY_LIMB_SIZE_BITS * limb_vec.size(),
APY_LIMB_SIZE_BITS * limb_vec.size(),
limb_vec
);
return *this >= rhs_fixed;
}
bool APyFixed::operator==(const double rhs) const
{
APyFloat rhs_fp(
sign_of_double(rhs), exp_of_double(rhs), man_of_double(rhs), 11, 52, 1023
);
return (*this == rhs_fp.to_fixed());
}
bool APyFixed::operator!=(const double rhs) const
{
APyFloat rhs_fp(
sign_of_double(rhs), exp_of_double(rhs), man_of_double(rhs), 11, 52, 1023
);
return (*this != rhs_fp.to_fixed());
}
bool APyFixed::operator<=(const double rhs) const
{
APyFloat rhs_fp(
sign_of_double(rhs), exp_of_double(rhs), man_of_double(rhs), 11, 52, 1023
);
return (*this <= rhs_fp.to_fixed());
}
bool APyFixed::operator<(const double rhs) const
{
APyFloat rhs_fp(
sign_of_double(rhs), exp_of_double(rhs), man_of_double(rhs), 11, 52, 1023
);
return (*this < rhs_fp.to_fixed());
}
bool APyFixed::operator>=(const double rhs) const
{
APyFloat rhs_fp(
sign_of_double(rhs), exp_of_double(rhs), man_of_double(rhs), 11, 52, 1023
);
return (*this >= rhs_fp.to_fixed());
}
bool APyFixed::operator>(const double rhs) const
{
APyFloat rhs_fp(
sign_of_double(rhs), exp_of_double(rhs), man_of_double(rhs), 11, 52, 1023
);
return (*this > rhs_fp.to_fixed());
}
APyFixed APyFixed::operator-() const
{
const int res_bits = _bits + 1;
APyFixed result(res_bits, _int_bits + 1);
if (unsigned(res_bits) <= APY_LIMB_SIZE_BITS) {
// Result bits fits in a single limb. Use native negation
result._data[0] = -_data[0];
} else {
// Invert all bits of *this, possibly append sign to new limb, and increment lsb
std::transform(
_data.cbegin(), _data.cend(), result._data.begin(), std::bit_not {}
);
if (result.vector_size() > vector_size()) {
apy_limb_t sign
= _data.back() & (apy_limb_t(1) << (APY_LIMB_SIZE_BITS - 1));
result._data.back() = sign ? 0 : apy_limb_signed_t(-1);
}
result.increment_lsb();
}
return result;
}
APyFixed APyFixed::operator~() const
{
APyFixed result(_bits, _int_bits);
std::transform(_data.cbegin(), _data.cend(), result._data.begin(), std::bit_not {});
return result;
}
APyFixed APyFixed::abs() const
{
const int res_bits = _bits + 1;
APyFixed result(res_bits, _int_bits + 1);
if (unsigned(res_bits) <= APY_LIMB_SIZE_BITS) {
result._data[0] = std::abs(apy_limb_signed_t(_data[0]));
} else {
limb_vector_abs(_data.begin(), _data.end(), result._data.begin());
}
return result;
}
/* ********************************************************************************** *
* * Public member functions * *
* ********************************************************************************** */
bool APyFixed::is_negative() const noexcept
{
return limb_vector_is_negative(_data.begin(), _data.end());
}
bool APyFixed::is_positive() const noexcept { return !is_negative() && !is_zero(); }
bool APyFixed::is_zero() const noexcept
{
return limb_vector_is_zero(std::begin(_data), std::end(_data));
}
// Increment the LSB without making the fixed-point number wider. Return carry out
apy_limb_t APyFixed::increment_lsb() noexcept
{
return apy_inplace_add_one_lsb(
&_data[0], // dst
vector_size() // limb vector length
);
}
// Function to create a Python fractions.Fraction object
nb::object APyFixed::to_fraction() const
{
nb::module_ fractions = nb::module_::import_("fractions");
nb::object Fraction = fractions.attr("Fraction");
if (is_zero()) {
return Fraction(0, 1);
}
auto trailing_zs = trailing_zeros();
auto frac_bits = this->frac_bits();
// Negative fractional bits special case
if (frac_bits <= 0) {
// Must add more bits to numerator
auto numerator = std::vector<apy_limb_t>(bits_to_limbs(bits() - frac_bits));
limb_vector_copy_sign_extend(
std::begin(_data),
std::end(_data),
std::begin(numerator),
std::end(numerator)
);
limb_vector_lsl(
std::begin(numerator), std::end(numerator), -frac_bits // shift amount
);
return Fraction(
python_limb_vec_to_long(numerator.begin(), numerator.end(), true), 1
);
}
// Copy numerator
auto numerator = std::vector<apy_limb_t>(_data.size());
limb_vector_copy_sign_extend(
std::begin(_data), std::end(_data), std::begin(numerator), std::end(numerator)
);
if (trailing_zs >= std::size_t(frac_bits)) {
// Integer result, get rid of fractional bits
limb_vector_asr(std::begin(numerator), std::end(numerator), frac_bits);
return Fraction(
python_limb_vec_to_long(numerator.begin(), numerator.end(), true), 1
);
}
// Remove the trailing zeros from numerator and denominator
limb_vector_asr(std::begin(numerator), std::end(numerator), trailing_zs);
// Create power-of-two denominator
auto denominator = std::vector<apy_limb_t>(
bits_to_limbs(std::size_t(frac_bits) - trailing_zs) + 2
);
denominator[0] = 1;
limb_vector_lsl(
std::begin(denominator),
std::end(denominator),
std::size_t(frac_bits) - trailing_zs
);
return Fraction(
python_limb_vec_to_long(numerator.begin(), numerator.end(), true),
python_limb_vec_to_long(denominator.begin(), denominator.end(), false)
);
}
// Function to create a Python fractions.Fraction object
nb::object APyFixed::as_integer_ratio() const
{
nb::module_ fractions = nb::module_::import_("fractions");
nb::object Fraction = fractions.attr("Fraction");
if (is_zero()) {
return nb::make_tuple(0, 1);
}
auto trailing_zs = trailing_zeros();
auto frac_bits = this->frac_bits();
// Negative fractional bits special case
if (frac_bits <= 0) {
// Must add more bits to numerator
auto numerator = std::vector<apy_limb_t>(bits_to_limbs(bits() - frac_bits));
limb_vector_copy_sign_extend(
std::begin(_data),
std::end(_data),
std::begin(numerator),
std::end(numerator)
);
limb_vector_lsl(
std::begin(numerator), std::end(numerator), -frac_bits // shift amount
);
return nb::make_tuple(
python_limb_vec_to_long(numerator.begin(), numerator.end(), true), 1
);
}
// Copy numerator
auto numerator = std::vector<apy_limb_t>(_data.size());
limb_vector_copy_sign_extend(
std::begin(_data), std::end(_data), std::begin(numerator), std::end(numerator)
);
if (trailing_zs >= std::size_t(frac_bits)) {
// Integer result, get rid of fractional bits
limb_vector_asr(std::begin(numerator), std::end(numerator), frac_bits);
return nb::make_tuple(
python_limb_vec_to_long(numerator.begin(), numerator.end(), true), 1
);
}
// Remove the trailing zeros from numerator and denominator
limb_vector_asr(std::begin(numerator), std::end(numerator), trailing_zs);
// Create power-of-two denominator
auto denominator = std::vector<apy_limb_t>(
bits_to_limbs(std::size_t(frac_bits) - trailing_zs) + 2
);
denominator[0] = 1;
limb_vector_lsl(
std::begin(denominator),
std::end(denominator),
std::size_t(frac_bits) - trailing_zs
);
return nb::make_tuple(
python_limb_vec_to_long(numerator.begin(), numerator.end(), true),
python_limb_vec_to_long(denominator.begin(), denominator.end(), false)
);
}
std::string APyFixed::to_string_dec() const
{
return fixed_point_to_string_dec(
std::begin(_data), std::end(_data), _bits, _int_bits
);
}
std::string APyFixed::to_string_hex() const
{
throw NotImplementedException("APyFixed::to_string_hex()");
}
std::string APyFixed::to_string_oct() const
{
throw NotImplementedException("APyFixed::to_string_oct()");
}
std::string APyFixed::to_string(int base) const
{
switch (base) {
case 10:
return to_string_dec();
default:
auto msg = fmt::format("APyFixed.__str__: base={} is not supported", base);
throw nb::value_error(msg.c_str());
}
}
APyFixed::operator double() const { return to_double(); }
void APyFixed::set_from_string_dec(const std::string& str)
{
// Trim the string from leading and trailing whitespace
std::string str_trimmed = string_trim_whitespace(str);
// Check the validity as a decimal string
if (!is_valid_decimal_numeric_string(str_trimmed)) {
throw nb::value_error("Not a valid decimal numeric string");
}
// Test if negative. If so, remove the negative sign from the string.
// `is_valid_decimal_numeric_string()` makes sure that str_trimmed[0] is valid.
bool is_negative = str_trimmed.front() == '-';
if (is_negative) {
str_trimmed.erase(0, 1);
}
// Trim leading and trailing zeros that don't affect the numeric value of the
// decimal number
str_trimmed = string_trim_zeros(str_trimmed);
// Find the binary point of the trimmed string and remove it from the string
std::size_t binary_point_dec = str_trimmed.find('.');
binary_point_dec = (binary_point_dec == std::string::npos) ? 0 : binary_point_dec;
str_trimmed.erase(
std::remove(str_trimmed.begin(), str_trimmed.end(), '.'), str_trimmed.end()
);
// Copy characters (from back) of the trimmed string into a BCD list
std::vector<uint8_t> bcd_list;
std::for_each(str_trimmed.crbegin(), str_trimmed.crend(), [&](char c) {
bcd_list.push_back(c - 0x30);
});
// Multiply BCD number by 2^(frac_bits() + 1) (extra bit for quantization)
auto bcd_list_size_prev = bcd_list.size();
for (int i = 0; i < frac_bits() + 1; i++) {
bcd_mul2(bcd_list);
}
// Remove elements after decimal dot
if (binary_point_dec) {
bcd_list.erase(
bcd_list.begin(), bcd_list.begin() + bcd_list_size_prev - binary_point_dec
);
}
// Reverse double-dabble algorithm (BCD -> binary)
std::vector<apy_limb_t> data = reverse_double_dabble(bcd_list);
// Round the data
apy_inplace_add_one_lsb(
&data[0], // dst
data.size() // limb vector length
);
apy_inplace_right_shift(
&data[0], // dst/src
data.size(), // limb vector length
1 // shift amount
);
// Adjust limb vector if negative fractional bits are present
if (frac_bits() + 1 < 0) {
limb_vector_asr(data.begin(), data.end(), -(frac_bits() + 1));
}
// Copy the data into the result vector
_data = data;
_data.resize(bits_to_limbs(bits()));
if (is_negative) {
limb_vector_negate_inplace(_data.begin(), _data.end());
}
// Two's complement overflow and we're done
_overflow_twos_complement(_data.begin(), _data.end(), bits(), int_bits());
}
void APyFixed::set_from_string_hex(const std::string& str)
{
(void)str;
throw NotImplementedException();
}
void APyFixed::set_from_string_oct(const std::string& str)
{
(void)str;
throw NotImplementedException("Not implemented: APyFixed::from_string_oct()");
}
void APyFixed::set_from_string(const std::string& str, int base)
{
switch (base) {
case 8:
set_from_string_oct(str);
break;
case 10:
set_from_string_dec(str);
break;
case 16:
set_from_string_hex(str);
break;
default:
throw NotImplementedException();
break;
}
}
double APyFixed::to_double() const
{
return fixed_point_to_double(std::begin(_data), std::end(_data), frac_bits());
}
nb::int_ APyFixed::to_bits() const
{
return python_limb_vec_to_long(
_data.begin(), _data.end(), false, bits() % APY_LIMB_SIZE_BITS
);
}
std::string APyFixed::bit_pattern_to_string_dec() const
{
std::stringstream ss {};
ScratchVector<apy_limb_t> data = _data;
if (bits() % APY_LIMB_SIZE_BITS) {
apy_limb_t and_mask = (apy_limb_t(1) << (bits() % APY_LIMB_SIZE_BITS)) - 1;
data.back() &= and_mask;
}
// Double-dabble for binary-to-BCD conversion
ss << bcds_to_string(double_dabble(static_cast<std::vector<apy_limb_t>>(data)));
return ss.str();
}
std::string APyFixed::repr() const
{
return fmt::format(
"APyFixed({}, bits={}, int_bits={})",
bit_pattern_to_string_dec(),
bits(),
int_bits()
);
}
std::string APyFixed::latex() const
{
if (this->is_negative()) {
APyFixed absval = abs();
return fmt::format(
"$-\\frac{{{}}}{{2^{{{}}}}} = {}$",
absval.bit_pattern_to_string_dec(),
frac_bits(),
to_string_dec()
);
}
return fmt::format(
"$\\frac{{{}}}{{2^{{{}}}}} = {}$",
bit_pattern_to_string_dec(),
frac_bits(),
to_string_dec()
);
}
bool APyFixed::is_identical(
const std::variant<const APyFixed*, const APyFixedArray*>& other
) const
{
if (!std::holds_alternative<const APyFixed*>(other)) {
return false;
} else {
auto&& other_scalar = *std::get<const APyFixed*>(other);
return bits() == other_scalar.bits() && int_bits() == other_scalar.int_bits()
&& *this == other_scalar;
}
}
std::size_t APyFixed::leading_zeros() const
{
std::size_t leading_zeros = limb_vector_leading_zeros(_data.begin(), _data.end());
if (leading_zeros == 0) {
return 0;
} else {
std::size_t utilized_bits_last_limb = ((bits() - 1) % APY_LIMB_SIZE_BITS) + 1;
return leading_zeros - (APY_LIMB_SIZE_BITS - utilized_bits_last_limb);
}
}
std::size_t APyFixed::leading_ones() const
{
std::size_t leading_ones = limb_vector_leading_ones(_data.begin(), _data.end());
if (leading_ones == 0) {
return 0;
} else {
std::size_t utilized_bits_last_limb = (bits() - 1) % APY_LIMB_SIZE_BITS + 1;
return leading_ones - (APY_LIMB_SIZE_BITS - utilized_bits_last_limb);
}
}
std::size_t APyFixed::trailing_zeros() const
{
std::size_t trailing_zeros = limb_vector_trailing_zeros(_data.begin(), _data.end());
return std::min(trailing_zeros, static_cast<std::size_t>(bits()));
}
std::size_t APyFixed::leading_fractional_zeros() const
{
int frac_bits = bits() - int_bits();
if (frac_bits <= 0) {
return 0; // early return
}
std::size_t utilized_full_frac_limbs = frac_bits / APY_LIMB_SIZE_BITS;
std::size_t utilized_frac_bits_last_limb = frac_bits % APY_LIMB_SIZE_BITS;
std::size_t leading_frac_bits_full_limbs = limb_vector_leading_zeros(
_data.begin(), _data.begin() + utilized_full_frac_limbs
);
std::size_t leading_frac_bits_last_limb = 0;
if (utilized_frac_bits_last_limb) {
apy_limb_t mask = (apy_limb_t(1) << utilized_frac_bits_last_limb) - 1;
apy_limb_t limb = _data[utilized_full_frac_limbs];
limb &= mask;
leading_frac_bits_last_limb = ::leading_zeros(limb)
- (APY_LIMB_SIZE_BITS - utilized_frac_bits_last_limb);
}
if (leading_frac_bits_last_limb != utilized_frac_bits_last_limb) {
return leading_frac_bits_last_limb;
} else {
return leading_frac_bits_last_limb + leading_frac_bits_full_limbs;
}
}
std::size_t APyFixed::leading_signs() const
{
return is_negative() ? leading_ones() : leading_zeros();
}
bool APyFixed::positive_greater_than_equal_pow2(int n) const
{
unsigned test_binary_point = std::max(0, frac_bits() + n);
return limb_vector_gte_pow2(_data.begin(), _data.end(), test_binary_point);
}
void APyFixed::set_bit_pow2(int n, bool bit)
{
const unsigned binary_point = std::max(0, frac_bits() + n);
limb_vector_set_bit(_data.begin(), _data.end(), binary_point, bit);
}
APyFixed APyFixed::pown(int n) const
{
if (n < 0) {
throw NotImplementedException("Not implemented: power with negative integers.");
}
if (n == 1) {
return *this;
}
if (n == 0) {
if (frac_bits() < 0) {
return APyFixed(int_bits(), int_bits(), { 1 });
} else {
return APyFixed(
bits(), int_bits(), { apy_limb_t(1) << (unsigned int)frac_bits() }
);
}
}
// Early exit for one of the most common cases
if (n == 2) {
return *this * *this;
}
auto result = ipow(n);
// Remove two integer bit as the starting value has two bits
return result.cast_no_overflow(result.bits() - 2, result.int_bits() - 2);
}
APyFixed APyFixed::ipow(unsigned int n) const
{
// Because how pown is written, we know n will be >= 3,
// this fact can probably be used to optimize this code further.
APyFixed base = *this;
APyFixed result = APyFixed(2, 2, { 1 });
for (;;) {
if (n & 1) {
result = result * base; // Until *= is implemented
}
n >>= 1;
if (!n) {
break;
}
base = base * base; // Until *= is implemented
}
return result;
}
/* ********************************************************************************** *
* * Static member functions * *
* ********************************************************************************** */
APyFixed APyFixed::from_number(
const nb::object& py_obj,
std::optional<int> int_bits,
std::optional<int> frac_bits,
std::optional<int> bits
)
{
if (nb::isinstance<nb::int_>(py_obj)) {
return APyFixed::from_integer(
nb::cast<nb::int_>(py_obj), int_bits, frac_bits, bits
);
} else if (nb::isinstance<nb::float_>(py_obj)) {
const auto d = static_cast<double>(nb::cast<nb::float_>(py_obj));
return APyFixed::from_double(d, int_bits, frac_bits, bits);
} else if (nb::isinstance<APyFixed>(py_obj)) {
const auto d = static_cast<APyFixed>(nb::cast<APyFixed>(py_obj));
return d.cast(
int_bits, frac_bits, QuantizationMode::RND_INF, OverflowMode::WRAP, bits
);
} else if (nb::isinstance<APyFloat>(py_obj)) {
const auto d = static_cast<APyFloat>(nb::cast<APyFloat>(py_obj));
return d.to_fixed().cast(
int_bits, frac_bits, QuantizationMode::RND_INF, OverflowMode::WRAP, bits
);
} else {
const nb::type_object type = nb::cast<nb::type_object>(py_obj.type());
const nb::str type_string = nb::str(type);
throw std::domain_error(
fmt::format("Non supported type: {}", type_string.c_str())
);
}
}