summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorzjpoh <poh.zijie@gmail.com>2019-08-07 23:03:08 -0700
committerzjpoh <poh.zijie@gmail.com>2019-08-07 23:03:08 -0700
commitb112fc371815fbd1fa5e1f121ffee9aa563092f1 (patch)
treeb75f76e2cd663cdca1ec7305e52e743155ce8701
parent67940ffec87b75ff72250ae9b2890fac6a134681 (diff)
downloadnumpy-b112fc371815fbd1fa5e1f121ffee9aa563092f1.tar.gz
Parse complex number from string
-rw-r--r--numpy/core/src/multiarray/arraytypes.c.src52
-rw-r--r--numpy/core/tests/test_longdouble.py13
2 files changed, 64 insertions, 1 deletions
diff --git a/numpy/core/src/multiarray/arraytypes.c.src b/numpy/core/src/multiarray/arraytypes.c.src
index 5d9e990e8..98939637c 100644
--- a/numpy/core/src/multiarray/arraytypes.c.src
+++ b/numpy/core/src/multiarray/arraytypes.c.src
@@ -1849,7 +1849,57 @@ BOOL_fromstr(char *str, void *ip, char **endptr,
}
/**begin repeat
- * #fname = CFLOAT, CDOUBLE, CLONGDOUBLE,
+ * #fname = CFLOAT, CDOUBLE#
+ * #type = npy_cfloat, npy_cdouble#
+ */
+static int
+@fname@_fromstr(char *str, void *ip, char **endptr,
+ PyArray_Descr *NPY_UNUSED(ignore))
+{
+ double result;
+
+ result = NumPyOS_ascii_strtod(str, endptr);
+
+ @type@ output;
+
+ if (endptr && (*endptr[0] == '+') || (*endptr[0] == '-')) {
+ // Imaginary component specified
+
+ output.real = result;
+
+ // Reading imaginary component
+ str = *endptr;
+ result = NumPyOS_ascii_strtod(str, endptr);
+
+ output.imag = result;
+
+ // Skip j
+ ++*endptr;
+ }
+ else if (endptr && *endptr[0] == 'j') {
+ // Real component not specified
+
+ output.real = 0;
+ output.imag = result;
+
+ // Skip j
+ ++*endptr;
+ }
+ else {
+ // Imaginary component not specified
+
+ output.real = result;
+ output.imag = 0.;
+ }
+
+ *(@type@ *)ip = output;
+ return 0;
+}
+/**end repeat**/
+
+
+/**begin repeat
+ * #fname = CLONGDOUBLE,
* OBJECT, STRING, UNICODE, VOID#
*/
diff --git a/numpy/core/tests/test_longdouble.py b/numpy/core/tests/test_longdouble.py
index ee4197f8f..ad4d7a357 100644
--- a/numpy/core/tests/test_longdouble.py
+++ b/numpy/core/tests/test_longdouble.py
@@ -70,6 +70,19 @@ def test_fromstring():
err_msg="reading '%s'" % s)
+def test_fromstring_complex():
+ for ctypes in ["cdouble", "cfloat"]:
+ # Check spacing between separator
+ assert_equal(np.fromstring("1, 2 , 3 ,4",sep=",",dtype=ctypes),
+ np.array([1., 2., 3., 4.]))
+ # Real component not specified
+ assert_equal(np.fromstring("1j, -2j, 3j, 4e1j",sep=",",dtype=ctypes),
+ np.array([1.j, -2.j, 3.j, 40.j]))
+ # Both components specified
+ assert_equal(np.fromstring("1+1j,2-2j, -3+3j, -4e1", sep=",", dtype=ctypes),
+ np.array([1. + 1.j, 2. - 2.j, - 3. + 3.j, - 40.]))
+
+
def test_fromstring_bogus():
assert_equal(np.fromstring("1. 2. 3. flop 4.", dtype=float, sep=" "),
np.array([1., 2., 3.]))