Skip to content

Commit a770387

Browse files
committed
BUG: Don't call float when constructing longdouble arrays
This addresses some of numpy#8902, preventing precision loss
1 parent 54487a8 commit a770387

2 files changed

Lines changed: 43 additions & 0 deletions

File tree

‎numpy/core/src/multiarray/arraytypes.c.src‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,20 @@ LONGDOUBLE_setitem(PyObject *op, void *ov, void *vap)
374374
/* ensure alignment */
375375
npy_longdouble temp;
376376

377+
/* Handle case of assigning from an array scalar */
378+
if (PyArray_Check(op) && PyArray_NDIM((PyArrayObject *)op) == 0) {
379+
PyObject *temp = PyArray_ToScalar(PyArray_BYTES((PyArrayObject *)op),
380+
(PyArrayObject *)op);
381+
if (temp == NULL) {
382+
return -1;
383+
}
384+
else {
385+
int res = LONGDOUBLE_setitem(temp, ov, ap);
386+
Py_DECREF(temp);
387+
return res;
388+
}
389+
}
390+
377391
if (PyArray_IsScalar(op, LongDouble)) {
378392
temp = ((PyLongDoubleScalarObject *)op)->obval;
379393
}

‎numpy/core/tests/test_multiarray.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,35 @@ def inject_str(s):
404404
# this would crash for the same reason
405405
np.array([np.array(u'\xe5\xe4\xf6')])
406406

407+
def test_longdouble_assignment(self):
408+
# only relevant if longdouble is larger than float
409+
# we're looking for loss of precision
410+
411+
# gh-8902
412+
tinyb = np.nextafter(np.longdouble(0), 1)
413+
tinya = np.nextafter(np.longdouble(0), -1)
414+
tiny1d = np.array([tinya])
415+
assert_equal(tiny1d[0], tinya)
416+
417+
# scalar = scalar
418+
tiny1d[0] = tinyb
419+
assert_equal(tiny1d[0], tinyb)
420+
421+
# 0d = scalar
422+
tiny1d[0, ...] = tinya
423+
assert_equal(tiny1d[0], tinya)
424+
425+
# 0d = 0d
426+
tiny1d[0, ...] = tinyb[...]
427+
assert_equal(tiny1d[0], tinyb)
428+
429+
# scalar = 0d
430+
tiny1d[0] = tinyb[...]
431+
assert_equal(tiny1d[0], tinyb)
432+
433+
arr = np.array([np.array(tinya)])
434+
assert_equal(arr[0], tinya)
435+
407436

408437
class TestDtypedescr(TestCase):
409438
def test_construction(self):

0 commit comments

Comments
 (0)