Skip to content

mpmath.mpc cannot convert string to complex #260

Description

@fredrik-johansson
# What steps will reproduce the problem?

>>> from mpmath import mpc
>>> mpc(str(mpc(1j)))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/mpmath/ctx_mp_python.py", line 373, in __new__
    real = cls.context.mpf(real)
  File "/usr/local/lib/python2.7/site-packages/mpmath/ctx_mp_python.py", line 77, in __new__
    v._mpf_ = mpf_pos(cls.mpf_convert_arg(val, prec, rounding), prec, rounding)
  File "/usr/local/lib/python2.7/site-packages/mpmath/ctx_mp_python.py", line 84, in mpf_convert_arg
    if isinstance(x, basestring): return from_str(x, prec, rounding)
  File "/usr/local/lib/python2.7/site-packages/mpmath/libmp/libmpf.py", line 1301, in from_str
    man, exp = str_to_man_exp(x, base=10)
  File "/usr/local/lib/python2.7/site-packages/mpmath/libmp/libmpf.py", line 1264, in str_to_man_exp
    float(x)
ValueError: could not convert string to float: (0.0 + 1.0j)

# What is the expected output? What do you see instead?
This should give 
mpc(real='0.0', imag='1.0')
and not raise ValueError.

# What version of the product are you using? On what operating system?
mpmath version 0.17, on FreeBSD 9.0-RC1

# Please provide any additional information below.
I am trying to build a generic input-output module that can read and write numbers, and gets only the desired type as setting. It would thus be nice to be able to use mpmath.mpc instead of __builtins__.complex in all instances. However, to generate an instance from a string, complex expects one string argument of the form complex("1+1j"), while mpmath.mpc needs to be called with two arguments as mpc("1","1j"), a calling convention which complex does not support.

_mpc.__new__ should not unconditionally pass every string to the mpf constructor, but should check if the string is of the form "(float)+(float)j", and in that case split at the "+" and construct the mpc from components of the split string.

Original issue for #260: http://code.google.com/p/mpmath/issues/detail?id=220
Original author: https://code.google.com/u/105994947365870677619/

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugan unexpected problem or unintended behaviorimported

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions