forked from numpy/numpy-quaddtype
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_quaddtype.py
More file actions
5750 lines (4783 loc) · 221 KB
/
test_quaddtype.py
File metadata and controls
5750 lines (4783 loc) · 221 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
import pytest
import sys
import numpy as np
import operator
from mpmath import mp
import numpy_quaddtype
from numpy_quaddtype import QuadPrecDType, QuadPrecision
from numpy_quaddtype import pi as quad_pi
def test_create_scalar_simple():
assert isinstance(QuadPrecision("12.0"), QuadPrecision)
assert isinstance(QuadPrecision(1.63), QuadPrecision)
assert isinstance(QuadPrecision(1), QuadPrecision)
@pytest.mark.parametrize("int_val", [
# Very large integers that exceed long double range
2 ** 1024,
2 ** 2048,
10 ** 308,
10 ** 4000,
# Edge cases
0,
1,
-1,
# Negative large integers
-(2 ** 1024),
])
def test_create_scalar_from_large_int(int_val):
"""Test that QuadPrecision can handle very large integers beyond long double range.
This test ensures that integers like 2**1024, which overflow standard long double,
are properly converted via string representation to QuadPrecision without raising
overflow errors. The conversion should match the string-based conversion.
"""
# Convert large int to QuadPrecision
result = QuadPrecision(int_val)
assert isinstance(result, QuadPrecision)
# String conversion should give the same result
str_val = str(int_val)
result_from_str = QuadPrecision(str_val)
# Both conversions should produce the same value
# (can be inf==inf on some platforms for very large values)
assert result == result_from_str
# For zero and small values, verify exact conversion
if int_val == 0:
assert float(result) == 0.0
elif abs(int_val) == 1:
assert float(result) == float(int_val)
def test_create_scalar_from_int_with_broken_str():
"""Test that QuadPrecision handles errors when __str__ fails on large integers.
This test checks the error handling path in scalar.c where PyObject_Str(py_int)
returns NULL. We simulate this by subclassing int with a __str__ method
that raises an exception.
"""
class BrokenInt(int):
def __str__(self):
raise RuntimeError("Intentionally broken __str__ method")
# Create an instance with a value that will overflow long long (> 2**63 - 1)
# This triggers the string conversion path in quad_from_py_int
broken_int = BrokenInt(2 ** 1024)
# When PyLong_AsLongLongAndOverflow returns overflow,
# it tries to convert to string, which should fail and propagate the error
with pytest.raises(RuntimeError, match="Intentionally broken __str__ method"):
QuadPrecision(broken_int)
class TestQuadPrecisionArrayCreation:
"""Test suite for QuadPrecision array creation from sequences and arrays."""
def test_create_array_from_list(self):
"""Test that QuadPrecision can create arrays from lists."""
# Test with simple list
result = QuadPrecision([3, 4, 5])
assert isinstance(result, np.ndarray)
assert result.dtype.name == "QuadPrecDType128"
assert result.shape == (3,)
np.testing.assert_array_equal(result, np.array([3, 4, 5], dtype=QuadPrecDType(backend='sleef')))
# Test with float list
result = QuadPrecision([1.5, 2.5, 3.5])
assert isinstance(result, np.ndarray)
assert result.dtype.name == "QuadPrecDType128"
assert result.shape == (3,)
np.testing.assert_array_equal(result, np.array([1.5, 2.5, 3.5], dtype=QuadPrecDType(backend='sleef')))
def test_create_array_from_tuple(self):
"""Test that QuadPrecision can create arrays from tuples."""
result = QuadPrecision((10, 20, 30))
assert isinstance(result, np.ndarray)
assert result.dtype.name == "QuadPrecDType128"
assert result.shape == (3,)
np.testing.assert_array_equal(result, np.array([10, 20, 30], dtype=QuadPrecDType(backend='sleef')))
def test_create_array_from_ndarray(self):
"""Test that QuadPrecision can create arrays from numpy arrays."""
arr = np.array([1, 2, 3, 4])
result = QuadPrecision(arr)
assert isinstance(result, np.ndarray)
assert result.dtype.name == "QuadPrecDType128"
assert result.shape == (4,)
np.testing.assert_array_equal(result, arr.astype(QuadPrecDType(backend='sleef')))
def test_create_2d_array_from_nested_list(self):
"""Test that QuadPrecision can create 2D arrays from nested lists."""
result = QuadPrecision([[1, 2], [3, 4]])
assert isinstance(result, np.ndarray)
assert result.dtype.name == "QuadPrecDType128"
assert result.shape == (2, 2)
expected = np.array([[1, 2], [3, 4]], dtype=QuadPrecDType(backend='sleef'))
np.testing.assert_array_equal(result, expected)
def test_create_array_with_backend(self):
"""Test that QuadPrecision respects backend parameter for arrays."""
# Test with sleef backend (default)
result_sleef = QuadPrecision([1, 2, 3], backend='sleef')
assert isinstance(result_sleef, np.ndarray)
assert result_sleef.dtype == QuadPrecDType(backend='sleef')
# Test with longdouble backend
result_ld = QuadPrecision([1, 2, 3], backend='longdouble')
assert isinstance(result_ld, np.ndarray)
assert result_ld.dtype == QuadPrecDType(backend='longdouble')
def test_quad_precision_array_vs_astype_equivalence(self):
"""Test that QuadPrecision(array) is equivalent to array.astype(QuadPrecDType)."""
test_arrays = [
[1, 2, 3],
[1.5, 2.5, 3.5],
[[1, 2], [3, 4]],
np.array([10, 20, 30]),
]
for arr in test_arrays:
result_quad = QuadPrecision(arr)
result_astype = np.array(arr).astype(QuadPrecDType(backend='sleef'))
np.testing.assert_array_equal(result_quad, result_astype)
assert result_quad.dtype == result_astype.dtype
def test_create_empty_array(self):
"""Test that QuadPrecision can create arrays from empty sequences."""
result = QuadPrecision([])
assert isinstance(result, np.ndarray)
assert result.dtype.name == "QuadPrecDType128"
assert result.shape == (0,)
expected = np.array([], dtype=QuadPrecDType(backend='sleef'))
np.testing.assert_array_equal(result, expected)
def test_create_from_numpy_int_scalars(self):
"""Test that QuadPrecision can create scalars from numpy integer types."""
# Test np.int32
result = QuadPrecision(np.int32(42))
assert isinstance(result, QuadPrecision)
assert float(result) == 42.0
# Test np.int64
result = QuadPrecision(np.int64(100))
assert isinstance(result, QuadPrecision)
assert float(result) == 100.0
# Test np.uint32
result = QuadPrecision(np.uint32(255))
assert isinstance(result, QuadPrecision)
assert float(result) == 255.0
# Test np.int8
result = QuadPrecision(np.int8(-128))
assert isinstance(result, QuadPrecision)
assert float(result) == -128.0
def test_create_from_numpy_float_scalars(self):
"""Test that QuadPrecision can create scalars from numpy floating types."""
# Test np.float64
result = QuadPrecision(np.float64(3.14))
assert isinstance(result, QuadPrecision)
assert abs(float(result) - 3.14) < 1e-10
# Test np.float32
result = QuadPrecision(np.float32(2.71))
assert isinstance(result, QuadPrecision)
# Note: float32 has limited precision, so we use a looser tolerance
assert abs(float(result) - 2.71) < 1e-5
# Test np.float16
result = QuadPrecision(np.float16(1.5))
assert isinstance(result, QuadPrecision)
assert abs(float(result) - 1.5) < 1e-3
def test_create_from_numpy_bool_scalars(self):
"""Test that QuadPrecision can create scalars from numpy boolean types."""
# Test np.bool_(True) converts to 1.0
result = QuadPrecision(np.bool_(True))
assert isinstance(result, QuadPrecision)
assert float(result) == 1.0
# Test np.bool_(False) converts to 0.0
result = QuadPrecision(np.bool_(False))
assert isinstance(result, QuadPrecision)
assert float(result) == 0.0
def test_create_from_zero_dimensional_array(self):
"""Test that QuadPrecision can create from 0-d numpy arrays."""
# 0-d array from scalar
arr_0d = np.array(5.5)
result = QuadPrecision(arr_0d)
assert isinstance(result, np.ndarray)
assert result.shape == () # 0-d array
assert result.dtype.name == "QuadPrecDType128"
expected = np.array(5.5, dtype=QuadPrecDType(backend='sleef'))
np.testing.assert_array_equal(result, expected)
# Another test with integer
arr_0d = np.array(42)
result = QuadPrecision(arr_0d)
assert isinstance(result, np.ndarray)
assert result.shape == ()
expected = np.array(42, dtype=QuadPrecDType(backend='sleef'))
np.testing.assert_array_equal(result, expected)
def test_numpy_scalar_with_backend(self):
"""Test that numpy scalars respect the backend parameter."""
# Test with sleef backend
result = QuadPrecision(np.int32(10), backend='sleef')
assert isinstance(result, QuadPrecision)
assert "backend='sleef'" in repr(result)
# Test with longdouble backend
result = QuadPrecision(np.float64(3.14), backend='longdouble')
assert isinstance(result, QuadPrecision)
assert "backend='longdouble'" in repr(result)
def test_numpy_scalar_types_coverage(self):
"""Test a comprehensive set of numpy scalar types."""
# Integer types
int_types = [
(np.int8, 10),
(np.int16, 1000),
(np.int32, 100000),
(np.int64, 10000000),
(np.uint8, 200),
(np.uint16, 50000),
(np.uint32, 4000000000),
]
for dtype, value in int_types:
result = QuadPrecision(dtype(value))
assert isinstance(result, QuadPrecision), f"Failed for {dtype.__name__}"
assert float(result) == float(value), f"Value mismatch for {dtype.__name__}"
# Float types
float_types = [
(np.float16, 1.5),
(np.float32, 2.5),
(np.float64, 3.5),
]
for dtype, value in float_types:
result = QuadPrecision(dtype(value))
assert isinstance(result, QuadPrecision), f"Failed for {dtype.__name__}"
# Use appropriate tolerance based on dtype precision
expected = float(dtype(value))
assert abs(float(result) - expected) < 1e-5, f"Value mismatch for {dtype.__name__}"
def test_string_roundtrip():
# Test with various values that require full quad precision
test_values = [
QuadPrecision("0.417022004702574000667425480060047"), # Random value
QuadPrecision("1.23456789012345678901234567890123456789"), # Many digits
numpy_quaddtype.pi, # Mathematical constant
numpy_quaddtype.e,
QuadPrecision("1e-100"), # Very small
QuadPrecision("1e100"), # Very large
QuadPrecision("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233"), # very precise pi
]
for original in test_values:
string_repr = str(original)
reconstructed = QuadPrecision(string_repr)
# Values should be exactly equal (bit-for-bit identical)
assert reconstructed == original, (
f"Round-trip failed for {repr(original)}:\n"
f" Original: {repr(original)}\n"
f" String: {string_repr}\n"
f" Reconstructed: {repr(reconstructed)}"
)
# Also verify repr() preserves value
repr_str = repr(original)
# Extract the string value from repr format: QuadPrecision('value', backend='...')
value_from_repr = repr_str.split("'")[1]
reconstructed_from_repr = QuadPrecision(value_from_repr)
assert reconstructed_from_repr == original, (
f"Round-trip from repr() failed for {repr(original)}"
)
class TestBytesSupport:
"""Test suite for QuadPrecision bytes input support."""
@pytest.mark.parametrize("original", [
QuadPrecision("0.417022004702574000667425480060047"), # Random value
QuadPrecision("1.23456789012345678901234567890123456789"), # Many digits
pytest.param(numpy_quaddtype.pi, id="pi"), # Mathematical constant
pytest.param(numpy_quaddtype.e, id="e"),
QuadPrecision("1e-100"), # Very small
QuadPrecision("1e100"), # Very large
QuadPrecision("-3.14159265358979323846264338327950288419"), # Negative pi
QuadPrecision("0.0"), # Zero
QuadPrecision("-0.0"), # Negative zero
QuadPrecision("1.0"), # One
QuadPrecision("-1.0"), # Negative one
])
def test_bytes_roundtrip(self, original):
"""Test that bytes representations of quad precision values roundtrip correctly."""
string_repr = str(original)
bytes_repr = string_repr.encode("ascii")
reconstructed = QuadPrecision(bytes_repr)
# Values should be exactly equal (bit-for-bit identical)
assert reconstructed == original, (
f"Bytes round-trip failed for {repr(original)}:\n"
f" Original: {repr(original)}\n"
f" Bytes: {bytes_repr}\n"
f" Reconstructed: {repr(reconstructed)}"
)
@pytest.mark.parametrize("bytes_val,expected_str", [
# Simple numeric values
(b"1.0", "1.0"),
(b"-1.0", "-1.0"),
(b"0.0", "0.0"),
(b"3.14159", "3.14159"),
# Scientific notation
(b"1e10", "1e10"),
(b"1e-10", "1e-10"),
(b"2.5e100", "2.5e100"),
(b"-3.7e-50", "-3.7e-50"),
])
def test_bytes_creation_basic(self, bytes_val, expected_str):
"""Test basic creation of QuadPrecision from bytes objects."""
assert QuadPrecision(bytes_val) == QuadPrecision(expected_str)
@pytest.mark.parametrize("bytes_val,check_func", [
# Very large and very small numbers
(b"1e308", lambda x: x == QuadPrecision("1e308")),
(b"1e-308", lambda x: x == QuadPrecision("1e-308")),
# Special values
(b"inf", lambda x: np.isinf(x)),
(b"-inf", lambda x: np.isinf(x) and x < 0),
(b"nan", lambda x: np.isnan(x)),
])
def test_bytes_creation_edge_cases(self, bytes_val, check_func):
"""Test edge cases for QuadPrecision creation from bytes."""
val = QuadPrecision(bytes_val)
assert check_func(val)
@pytest.mark.parametrize("invalid_bytes", [
b"", # Empty bytes
b"not_a_number", # Invalid format
b"1.23abc", # Trailing garbage
b"abc1.23", # Leading garbage
])
def test_bytes_invalid_input(self, invalid_bytes):
"""Test that invalid bytes input raises appropriate errors."""
with pytest.raises(ValueError, match="Unable to parse bytes to QuadPrecision"):
QuadPrecision(invalid_bytes)
@pytest.mark.parametrize("backend", ["sleef", "longdouble"])
@pytest.mark.parametrize("bytes_val", [
b"1.0",
b"-1.0",
b"3.141592653589793238462643383279502884197",
b"1e100",
b"1e-100",
b"0.0",
])
def test_bytes_backend_consistency(self, backend, bytes_val):
"""Test that bytes parsing works consistently across backends."""
quad_val = QuadPrecision(bytes_val, backend=backend)
str_val = QuadPrecision(bytes_val.decode("ascii"), backend=backend)
# Bytes and string should produce identical results
assert quad_val == str_val, (
f"Backend {backend}: bytes and string parsing differ for {bytes_val}\n"
f" From bytes: {repr(quad_val)}\n"
f" From string: {repr(str_val)}"
)
@pytest.mark.parametrize("bytes_val,expected_str", [
# Leading whitespace is OK (consumed by parser)
(b" 1.0", "1.0"),
(b" 3.14", "3.14"),
# Trailing whitespace is OK (matches Python's float() behavior)
(b"1.0 ", "1.0"),
(b"1.0 ", "1.0"),
])
def test_bytes_whitespace_valid(self, bytes_val, expected_str):
"""Test handling of valid whitespace in bytes input."""
assert QuadPrecision(bytes_val) == QuadPrecision(expected_str)
@pytest.mark.parametrize("invalid_bytes", [
b"1 .0", # Internal whitespace
b"1. 0", # Internal whitespace
])
def test_bytes_whitespace_invalid(self, invalid_bytes):
"""Test that invalid whitespace in bytes input raises errors."""
with pytest.raises(ValueError, match="Unable to parse bytes to QuadPrecision"):
QuadPrecision(invalid_bytes)
@pytest.mark.parametrize("test_str", [
"1.0",
"-3.14159265358979323846264338327950288419",
"1e100",
"2.71828182845904523536028747135266249775",
])
def test_bytes_encoding_compatibility(self, test_str):
"""Test that bytes created from different encodings work correctly."""
from_string = QuadPrecision(test_str)
from_bytes = QuadPrecision(test_str.encode("ascii"))
from_bytes_utf8 = QuadPrecision(test_str.encode("utf-8"))
assert from_string == from_bytes
assert from_string == from_bytes_utf8
def test_string_subclass_parsing():
"""Test that QuadPrecision handles string subclasses correctly.
This tests the PyUnicode_Check path in scalar.c lines 195-209,
verifying that string subclasses work and that parsing errors
are properly handled.
"""
class MyString(str):
"""A custom string subclass"""
pass
# Test valid string subclass - should parse correctly
valid_str = MyString("3.14159265358979323846")
result = QuadPrecision(valid_str)
assert isinstance(result, QuadPrecision)
expected = QuadPrecision("3.14159265358979323846")
assert result == expected
# Test with scientific notation
sci_str = MyString("1.23e-100")
result = QuadPrecision(sci_str)
assert isinstance(result, QuadPrecision)
# Test with negative value
neg_str = MyString("-42.5")
result = QuadPrecision(neg_str)
assert float(result) == -42.5
# Test invalid string - should raise ValueError
invalid_str = MyString("not a number")
with pytest.raises(ValueError, match="Unable to parse string to QuadPrecision"):
QuadPrecision(invalid_str)
# Test partially valid string (has trailing garbage)
partial_str = MyString("3.14abc")
with pytest.raises(ValueError, match="Unable to parse string to QuadPrecision"):
QuadPrecision(partial_str)
# Test empty string
empty_str = MyString("")
with pytest.raises(ValueError, match="Unable to parse string to QuadPrecision"):
QuadPrecision(empty_str)
# Test string with leading garbage
leading_garbage = MyString("abc3.14")
with pytest.raises(ValueError, match="Unable to parse string to QuadPrecision"):
QuadPrecision(leading_garbage)
# Test special values
inf_str = MyString("inf")
result = QuadPrecision(inf_str)
assert np.isinf(float(result))
neg_inf_str = MyString("-inf")
result = QuadPrecision(neg_inf_str)
assert np.isinf(float(result)) and float(result) < 0
nan_str = MyString("nan")
result = QuadPrecision(nan_str)
assert np.isnan(float(result))
@pytest.mark.parametrize("name,expected", [("pi", np.pi), ("e", np.e), ("log2e", np.log2(np.e)), ("log10e", np.log10(np.e)), ("ln2", np.log(2.0)), ("ln10", np.log(10.0))])
def test_math_constant(name, expected):
assert isinstance(getattr(numpy_quaddtype, name), QuadPrecision)
assert np.float64(getattr(numpy_quaddtype, name)) == expected
def test_smallest_subnormal_value():
"""Test that smallest_subnormal has the correct value across all platforms."""
smallest_sub = numpy_quaddtype.smallest_subnormal
repr_str = repr(smallest_sub)
# The repr should show QuadPrecision('6.0e-4966', backend='sleef')
assert "6.0e-4966" in repr_str, f"Expected '6.0e-4966' in repr, got {repr_str}"
assert smallest_sub > 0, "smallest_subnormal should be positive"
@pytest.mark.parametrize("dtype", [
"bool",
"byte", "int8", "ubyte", "uint8",
"short", "int16", "ushort", "uint16",
"int", "int32", "uint", "uint32",
"long", "ulong",
"longlong", "int64", "ulonglong", "uint64",
"half", "float16",
"float", "float32",
"double", "float64",
"longdouble", "float96", "float128",
])
def test_supported_astype(dtype):
if dtype in ("float96", "float128") and getattr(np, dtype, None) is None:
pytest.skip(f"{dtype} is unsupported on the current platform")
orig = np.array(1, dtype=dtype)
quad = orig.astype(QuadPrecDType, casting="safe")
back = quad.astype(dtype, casting="unsafe")
assert quad == 1
assert back == orig
@pytest.mark.parametrize("dtype", ["V10", "datetime64[ms]", "timedelta64[ms]"])
def test_unsupported_astype(dtype):
if dtype == "V10":
with pytest.raises(TypeError, match="cast"):
np.ones((3, 3), dtype="V10").astype(QuadPrecDType, casting="unsafe")
else:
with pytest.raises(TypeError, match="cast"):
np.array(1, dtype=dtype).astype(QuadPrecDType, casting="unsafe")
with pytest.raises(TypeError, match="cast"):
np.array(QuadPrecision(1)).astype(dtype, casting="unsafe")
class TestArrayCastStringBytes:
@pytest.mark.parametrize("strtype", [np.str_, str, np.dtypes.StringDType()])
@pytest.mark.parametrize("input_val", [
"3.141592653589793238462643383279502884197",
"2.71828182845904523536028747135266249775",
"1e100",
"1e-100",
"0.0",
"-0.0",
"inf",
"-inf",
"nan",
"-nan",
])
def test_cast_string_to_quad_roundtrip(self, input_val, strtype):
str_array = np.array(input_val, dtype=strtype)
quad_array = str_array.astype(QuadPrecDType())
expected = np.array(input_val, dtype=QuadPrecDType())
if np.isnan(float(expected)):
np.testing.assert_array_equal(np.isnan(quad_array), np.isnan(expected))
else:
np.testing.assert_array_equal(quad_array, expected)
quad_to_string_array = quad_array.astype(strtype)
# Round-trip - String -> Quad -> String -> Quad should preserve value
roundtrip_quad_array = quad_to_string_array.astype(QuadPrecDType())
if np.isnan(float(expected)):
np.testing.assert_array_equal(np.isnan(roundtrip_quad_array), np.isnan(quad_array))
else:
np.testing.assert_array_equal(roundtrip_quad_array, quad_array,
err_msg=f"Round-trip failed for {input_val}")
# Verify the string representation can be parsed back
# (This ensures the quad->string cast produces valid parseable strings)
scalar_str = str(quad_array[()])
scalar_from_str = QuadPrecision(scalar_str)
if np.isnan(float(quad_array[()])):
assert np.isnan(float(scalar_from_str))
else:
assert scalar_from_str == quad_array[()], \
f"Scalar round-trip failed: {scalar_str} -> {scalar_from_str} != {quad_array[()]}"
@pytest.mark.parametrize("input_val", [
b"3.141592653589793238462643383279502884197",
b"2.71828182845904523536028747135266249775",
b"1e100",
b"1e-100",
b"0.0",
b"-0.0",
b"inf",
b"-inf",
b"nan",
b"-nan",
])
def test_cast_bytes_to_quad_roundtrip(self, input_val):
"""Test bytes -> quad -> bytes round-trip conversion"""
bytes_array = np.array(input_val, dtype='S50')
quad_array = bytes_array.astype(QuadPrecDType())
expected = np.array(input_val.decode('utf-8'), dtype=QuadPrecDType())
if np.isnan(float(expected)):
np.testing.assert_array_equal(np.isnan(quad_array), np.isnan(expected))
else:
np.testing.assert_array_equal(quad_array, expected)
quad_to_bytes_array = quad_array.astype('S50')
# Round-trip - Bytes -> Quad -> Bytes -> Quad should preserve value
roundtrip_quad_array = quad_to_bytes_array.astype(QuadPrecDType())
if np.isnan(float(expected)):
np.testing.assert_array_equal(np.isnan(roundtrip_quad_array), np.isnan(quad_array))
else:
np.testing.assert_array_equal(roundtrip_quad_array, quad_array,
err_msg=f"Round-trip failed for {input_val}")
@pytest.mark.parametrize("dtype_str", ['S10', 'S20', 'S30', 'S50', 'S100'])
def test_bytes_different_sizes(self, dtype_str):
"""Test bytes casting with different buffer sizes"""
quad_val = np.array([1.23456789012345678901234567890], dtype=QuadPrecDType())
bytes_val = quad_val.astype(dtype_str)
# Should not raise error
assert bytes_val.dtype.str.startswith('|S')
# Should be able to parse back
roundtrip = bytes_val.astype(QuadPrecDType())
# For smaller sizes, precision may be truncated, so use approximate comparison
# For larger sizes (S50+), should be exact
if dtype_str in ['S50', 'S100']:
np.testing.assert_array_equal(roundtrip, quad_val)
else:
# Smaller sizes may lose precision due to string truncation
np.testing.assert_allclose(roundtrip, quad_val, rtol=1e-8)
@pytest.mark.parametrize("input_bytes", [
b'1.5',
b'2.25',
b'3.14159265358979323846',
b'-1.5',
b'-2.25',
b'1.23e50',
b'-4.56e-100',
])
def test_bytes_to_quad_basic_values(self, input_bytes):
"""Test basic numeric bytes to quad conversion"""
bytes_array = np.array([input_bytes], dtype='S50')
quad_array = bytes_array.astype(QuadPrecDType())
# Should successfully convert
assert quad_array.dtype.name == "QuadPrecDType128"
# Value should match string conversion
str_val = input_bytes.decode('utf-8')
expected = QuadPrecision(str_val)
assert quad_array[0] == expected
@pytest.mark.parametrize("special_bytes,check_func", [
(b'inf', lambda x: np.isinf(float(str(x))) and float(str(x)) > 0),
(b'-inf', lambda x: np.isinf(float(str(x))) and float(str(x)) < 0),
(b'nan', lambda x: np.isnan(float(str(x)))),
(b'Infinity', lambda x: np.isinf(float(str(x))) and float(str(x)) > 0),
(b'-Infinity', lambda x: np.isinf(float(str(x))) and float(str(x)) < 0),
(b'NaN', lambda x: np.isnan(float(str(x)))),
])
def test_bytes_special_values(self, special_bytes, check_func):
"""Test special values (inf, nan) in bytes format"""
bytes_array = np.array([special_bytes], dtype='S20')
quad_array = bytes_array.astype(QuadPrecDType())
assert check_func(quad_array[0]), f"Failed for {special_bytes}"
def test_bytes_array_vectorized(self):
"""Test vectorized bytes to quad conversion"""
bytes_array = np.array([b'1.5', b'2.25', b'3.14159', b'-1.0', b'1e100'], dtype='S50')
quad_array = bytes_array.astype(QuadPrecDType())
assert quad_array.shape == (5,)
assert quad_array.dtype.name == "QuadPrecDType128"
# Check individual values
assert quad_array[0] == QuadPrecision('1.5')
assert quad_array[1] == QuadPrecision('2.25')
assert quad_array[2] == QuadPrecision('3.14159')
assert quad_array[3] == QuadPrecision('-1.0')
assert quad_array[4] == QuadPrecision('1e100')
def test_quad_to_bytes_preserves_precision(self):
"""Test that quad to bytes conversion preserves high precision"""
# Use a high-precision value
quad_val = np.array([QuadPrecision("3.141592653589793238462643383279502884197")],
dtype=QuadPrecDType())
bytes_val = quad_val.astype('S50')
# Convert back and verify precision is maintained
roundtrip = bytes_val.astype(QuadPrecDType())
np.testing.assert_array_equal(roundtrip, quad_val)
@pytest.mark.parametrize("invalid_bytes", [
b'not_a_number',
b'1.23.45',
b'abc123',
b'1e',
b'++1.0',
b'1.0abc',
])
def test_invalid_bytes_raise_error(self, invalid_bytes):
"""Test that invalid bytes raise ValueError"""
bytes_array = np.array([invalid_bytes], dtype='S50')
with pytest.raises(ValueError, match="could not convert bytes to QuadPrecision"):
bytes_array.astype(QuadPrecDType())
def test_bytes_with_null_terminator(self):
"""Test bytes with embedded null terminators are handled correctly"""
# Bytes arrays can have null padding
bytes_array = np.array([b'1.5'], dtype='S20')
# This creates a 20-byte array with '1.5' followed by null bytes
quad_array = bytes_array.astype(QuadPrecDType())
assert quad_array[0] == QuadPrecision('1.5')
def test_empty_bytes_raises_error(self):
"""Test that empty bytes raise ValueError"""
bytes_array = np.array([b''], dtype='S50')
with pytest.raises(ValueError):
bytes_array.astype(QuadPrecDType())
@pytest.mark.parametrize("strtype", [np.str_, np.dtypes.StringDType()])
@pytest.mark.parametrize("backend", ["sleef", "longdouble"])
def test_string_backend_consistency(self, strtype, backend):
"""Test that string parsing works consistently across backends"""
input_str = "3.141592653589793238462643383279502884197"
str_array = np.array([input_str], dtype=strtype)
quad_array = str_array.astype(QuadPrecDType(backend=backend))
scalar_val = QuadPrecision(input_str, backend=backend)
np.testing.assert_array_equal(quad_array, np.array([scalar_val], dtype=QuadPrecDType(backend=backend)))
@pytest.mark.parametrize("strtype", [np.str_, np.dtypes.StringDType()])
def test_string_large_array(self, strtype):
"""Test conversion of large string array"""
str_values = [str(i * 0.001) for i in range(1000)]
str_array = np.array(str_values, dtype=strtype)
quad_array = str_array.astype(QuadPrecDType())
assert quad_array.shape == (1000,)
np.testing.assert_array_equal(quad_array, np.array(str_values, dtype=QuadPrecDType()))
class TestStringParsingEdgeCases:
"""Test edge cases in NumPyOS_ascii_strtoq string parsing"""
@pytest.mark.parametrize("input_str", ['3.14', '-2.71', '0.0', '1e10', '-1e-10'])
@pytest.mark.parametrize("byte_order", ['<', '>'])
def test_numeric_string_parsing(self, input_str, byte_order):
"""Test that numeric strings are parsed correctly regardless of byte order"""
strtype = np.dtype(f'{byte_order}U20')
arr = np.array([input_str], dtype=strtype)
result = arr.astype(QuadPrecDType())
expected = np.array(input_str, dtype=np.float64)
np.testing.assert_allclose(result, expected,
err_msg=f"Failed parsing '{input_str}' with byte order '{byte_order}'")
@pytest.mark.parametrize("input_str,expected_sign", [
("inf", 1),
("+inf", 1),
("-inf", -1),
("Inf", 1),
("+Inf", 1),
("-Inf", -1),
("INF", 1),
("+INF", 1),
("-INF", -1),
("infinity", 1),
("+infinity", 1),
("-infinity", -1),
("Infinity", 1),
("+Infinity", 1),
("-Infinity", -1),
("INFINITY", 1),
("+INFINITY", 1),
("-INFINITY", -1),
])
@pytest.mark.parametrize("strtype", ['U20', np.dtypes.StringDType()])
def test_infinity_sign_preservation(self, input_str, expected_sign, strtype):
"""Test that +/- signs are correctly applied to infinity values"""
arr = np.array([input_str], dtype=strtype)
result = arr.astype(QuadPrecDType())
assert np.isinf(float(str(result[0]))), f"Expected inf for '{input_str}'"
actual_sign = 1 if float(str(result[0])) > 0 else -1
assert actual_sign == expected_sign, \
f"Sign mismatch for '{input_str}': got {actual_sign}, expected {expected_sign}"
@pytest.mark.parametrize("input_str", [
"nan", "+nan", "-nan", # Note: NaN sign is typically ignored
"NaN", "+NaN", "-NaN",
"NAN", "+NAN", "-NAN",
"nan()", "nan(123)", "nan(abc_)", "NAN(XYZ)",
])
@pytest.mark.parametrize("strtype", ['U20', np.dtypes.StringDType()])
def test_nan_case_insensitive(self, input_str, strtype):
"""Test case-insensitive NaN parsing with optional payloads"""
arr = np.array([input_str], dtype=strtype)
result = arr.astype(QuadPrecDType())
assert np.isnan(float(str(result[0]))), f"Expected NaN for '{input_str}'"
@pytest.mark.parametrize("input_str,expected_val", [
("3.14", 3.14),
("+3.14", 3.14),
("-3.14", -3.14),
("0.0", 0.0),
("+0.0", 0.0),
("-0.0", -0.0),
("1e10", 1e10),
("+1e10", 1e10),
("-1e10", -1e10),
("1.23e-45", 1.23e-45),
("+1.23e-45", 1.23e-45),
("-1.23e-45", -1.23e-45),
])
@pytest.mark.parametrize("strtype", ['U20', np.dtypes.StringDType()])
def test_numeric_sign_handling(self, input_str, expected_val, strtype):
"""Test that +/- signs are correctly handled for numeric values"""
arr = np.array([input_str], dtype=strtype)
result = arr.astype(QuadPrecDType())
result_val = float(str(result[0]))
# For zero, check sign separately
if expected_val == 0.0:
assert result_val == 0.0
if input_str.startswith('-'):
assert np.signbit(result_val), f"Expected negative zero for '{input_str}'"
else:
assert not np.signbit(result_val), f"Expected positive zero for '{input_str}'"
else:
np.testing.assert_allclose(result_val, expected_val, rtol=1e-10)
@pytest.mark.parametrize("input_str", [
" 3.14 ",
"\t3.14\t",
"\n3.14\n",
"\r3.14\r",
" \t\n\r 3.14 \t\n\r ",
" inf ",
"\t-inf\t",
" nan ",
])
@pytest.mark.parametrize("strtype", ['U20', np.dtypes.StringDType()])
def test_whitespace_handling(self, input_str, strtype):
"""Test that leading/trailing whitespace is handled correctly"""
arr = np.array([input_str], dtype=strtype)
result = arr.astype(QuadPrecDType())
# Should not raise an error
result_str = str(result[0])
assert result_str # Should have a value
@pytest.mark.parametrize("invalid_str", [
"abc", # Non-numeric
"3.14.15", # Multiple decimals
"1.23e", # Incomplete scientific notation
"e10", # Scientific notation without base
"3.14abc", # Trailing non-numeric
"++3.14", # Double sign
"--3.14", # Double sign
"+-3.14", # Mixed signs
"in", # Incomplete inf
"na", # Incomplete nan
"infinit", # Incomplete infinity
])
@pytest.mark.parametrize("strtype", ['U20', np.dtypes.StringDType()])
def test_invalid_strings_raise_error(self, invalid_str, strtype):
"""Test that invalid strings raise ValueError"""
arr = np.array([invalid_str], dtype=strtype)
with pytest.raises(ValueError):
arr.astype(QuadPrecDType())
@pytest.mark.parametrize("input_str", [
"3.14ñ", # Trailing non-ASCII
"ñ3.14", # Leading non-ASCII
"3.1€4", # Mid non-ASCII
"π", # Greek pi
])
@pytest.mark.parametrize("strtype", ['U20', np.dtypes.StringDType()])
def test_non_ascii_raises_error(self, input_str, strtype):
"""Test that non-ASCII characters raise ValueError"""
arr = np.array([input_str], dtype=strtype)
with pytest.raises(ValueError):
arr.astype(QuadPrecDType())
def test_numpy_longdouble_compatibility(self):
"""Test that our parsing matches NumPy's longdouble for common cases"""
test_cases = [
"inf", "INF", "Inf", "-inf", "+infinity",
"nan", "NAN", "NaN",
"3.14", "-2.718", "1e10", "-1.23e-45",
]
for test_str in test_cases:
arr = np.array([test_str], dtype='U20')
# NumPy's built-in
np_result = arr.astype(np.longdouble)
# Our QuadPrecision
quad_result = arr.astype(QuadPrecDType())
np_val = np_result[0]
quad_val = float(str(quad_result[0]))
if np.isnan(np_val):
assert np.isnan(quad_val), f"NumPy gives NaN but QuadPrec doesn't for '{test_str}'"
elif np.isinf(np_val):
assert np.isinf(quad_val), f"NumPy gives inf but QuadPrec doesn't for '{test_str}'"
assert np.sign(np_val) == np.sign(quad_val), \
f"Inf sign mismatch for '{test_str}': NumPy={np.sign(np_val)}, Quad={np.sign(quad_val)}"
else:
np.testing.assert_allclose(quad_val, np_val, rtol=1e-10)
def test_locale_independence(self):
"""Test that parsing always uses '.' for decimal, not locale-specific separator"""
# This should parse correctly (period as decimal)
arr = np.array(["3.14"], dtype='U20')
result = arr.astype(QuadPrecDType())
assert float(str(result[0])) == 3.14
# In some locales ',' is decimal separator, but we should always use '.'
# So "3,14" should either error or parse as "3" (stopping at comma)
# Since require_full_parse validation happens in casts.cpp, and we check
# for trailing content, this should raise ValueError
arr_comma = np.array(["3,14"], dtype='U20')
with pytest.raises(ValueError):
arr_comma.astype(QuadPrecDType())
@pytest.mark.parametrize("input_str,description", [
(" 1.23 ", "space - leading and trailing"),
("\t1.23\t", "tab - leading and trailing"),
("\n1.23\n", "newline - leading and trailing"),
("\r1.23\r", "carriage return - leading and trailing"),
("\v1.23\v", "vertical tab - leading and trailing"),
("\f1.23\f", "form feed - leading and trailing"),
(" \t\n\r\v\f1.23 \t\n\r\v\f", "all 6 whitespace chars - mixed"),
("\t\t\t3.14\t\t\t", "multiple tabs"),
(" inf ", "infinity with spaces"),
("\t\t-inf\t\t", "negative infinity with tabs"),
("\n\nnan\n\n", "nan with newlines"),
("\r\r-nan\r\r", "negative nan with carriage returns"),
("\v\v1e10\v\v", "scientific notation with vertical tabs"),
("\f\f-1.23e-45\f\f", "negative scientific with form feeds"),
])
def test_all_six_whitespace_characters(self, input_str, description):
"""Test all 6 ASCII whitespace characters (space, tab, newline, carriage return, vertical tab, form feed)
This tests the ascii_isspace() helper function in casts.cpp which matches
CPython's Py_ISSPACE and NumPy's NumPyOS_ascii_isspace behavior.
The 6 characters are: 0x09(\t), 0x0A(\n), 0x0B(\v), 0x0C(\f), 0x0D(\r), 0x20(space)
"""
arr = np.array([input_str], dtype='U50')
result = arr.astype(QuadPrecDType())
# Should successfully parse without errors
result_val = str(result[0])
assert result_val, f"Failed to parse with {description}"
# Verify the value is correct (strip whitespace and compare)
stripped = input_str.strip(' \t\n\r\v\f')
expected_arr = np.array([stripped], dtype='U50')
expected = expected_arr.astype(QuadPrecDType())
if np.isnan(float(str(expected[0]))):
assert np.isnan(float(str(result[0]))), f"NaN parsing failed for {description}"