[Python-ideas] Yet another sum function (fractions.sum)

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed Aug 21 19:27:46 CEST 2013


On 21 August 2013 18:06, MRAB <python at mrabarnett.plus.com> wrote:
> On 21/08/2013 15:19, random832 at fastmail.us wrote:
>>
>> On Tue, Aug 20, 2013, at 18:47, Andrew Barnert wrote:
>>>
>>> So instead of math.sqrt and cmath.sqrt, we just have one function that
>>> decides whether sqrt(-1) is 0+1j or an exception based on guessing
>>> whether you wanted complex numbers? :)
>>
>> Why exactly is an exception reasonable? If you don't want complex
>> numbers, don't take square roots of negative numbers. If you can't
>> handle complex numbers, you'll get an exception down the line anyway.
>>
> I think a simpler rule might be: if the argument is a float then the
> result is a float; if the argument is complex then the result is
> complex.

I like the fact that math.sqrt() raises an error for negative numbers.
That error message has been far more useful to me than cmath.sqrt()
ever has.

> If that's the case, then do we really need to keep them separate,
> having math and cmath?

And what if the argument's an int? Does the int duck-type as a float
or a complex? Or should it raise an error if the root is not an
integer?

I feel like I'd end up writing:
    math.sqrt(a + 0j)
when I want to get complex roots. Definitely
   cmath.sqrt(a)
is better.

The problem I have with sqrt(int) is that it doesn't raise an error
and just produces an inaccurate result. Fixing that for the cases
where exact results are available could be a big performance
regression for some people. Anyway I'd rather use an alternative
sqrt_exact() that wasn't expected to be fast but was guaranteed to be
accurate or to raise an error.


Oscar


More information about the Python-ideas mailing list