Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #68367 > unrolled thread
| Started by | Jayanth Koushik <jnkoushik@gmail.com> |
|---|---|
| First post | 2014-03-15 09:26 -0700 |
| Last post | 2014-03-18 16:00 +0200 |
| Articles | 20 on this page of 33 — 11 participants |
Back to article view | Back to comp.lang.python
'complex' function with string argument. Jayanth Koushik <jnkoushik@gmail.com> - 2014-03-15 09:26 -0700
Re: 'complex' function with string argument. Mark H Harris <harrismh777@gmail.com> - 2014-03-17 11:18 -0500
Re: 'complex' function with string argument. Chris Angelico <rosuav@gmail.com> - 2014-03-18 04:03 +1100
Re: 'complex' function with string argument. Marko Rauhamaa <marko@pacujo.net> - 2014-03-17 20:15 +0200
Re: 'complex' function with string argument. Ian Kelly <ian.g.kelly@gmail.com> - 2014-03-17 12:28 -0600
Re: 'complex' function with string argument. Chris Angelico <rosuav@gmail.com> - 2014-03-18 05:59 +1100
Re: 'complex' function with string argument. Marko Rauhamaa <marko@pacujo.net> - 2014-03-17 21:22 +0200
Re: 'complex' function with string argument. Chris Angelico <rosuav@gmail.com> - 2014-03-18 06:32 +1100
Re: 'complex' function with string argument. Steven D'Aprano <steve@pearwood.info> - 2014-03-18 04:08 +0000
Re: 'complex' function with string argument. Mark H Harris <harrismh777@gmail.com> - 2014-03-17 13:20 -0500
Re: 'complex' function with string argument. Steven D'Aprano <steve@pearwood.info> - 2014-03-18 04:52 +0000
Re: 'complex' function with string argument. Chris Angelico <rosuav@gmail.com> - 2014-03-18 15:59 +1100
Re: 'complex' function with string argument. Mark H Harris <harrismh777@gmail.com> - 2014-03-18 11:14 -0500
Re: 'complex' function with string argument. wxjmfauth@gmail.com - 2014-03-19 00:30 -0700
Re: 'complex' function with string argument. Marko Rauhamaa <marko@pacujo.net> - 2014-03-19 10:51 +0200
Re: 'complex' function with string argument. wxjmfauth@gmail.com - 2014-03-19 02:52 -0700
Re: 'complex' function with string argument. Marko Rauhamaa <marko@pacujo.net> - 2014-03-19 12:09 +0200
Re: 'complex' function with string argument. Ian Kelly <ian.g.kelly@gmail.com> - 2014-03-19 04:33 -0600
Re: 'complex' function with string argument. Marko Rauhamaa <marko@pacujo.net> - 2014-03-19 12:53 +0200
Re: 'complex' function with string argument. Ian Kelly <ian.g.kelly@gmail.com> - 2014-03-19 13:35 -0600
Re: 'complex' function with string argument. Skip Montanaro <skip@pobox.com> - 2014-03-19 06:04 -0500
Re: 'complex' function with string argument. wxjmfauth@gmail.com - 2014-03-19 07:35 -0700
Re: 'complex' function with string argument. Ian Kelly <ian.g.kelly@gmail.com> - 2014-03-19 12:45 -0600
Re: 'complex' function with string argument. Mark Dickinson <mdickinson@enthought.com> - 2014-03-17 17:55 +0000
Re: 'complex' function with string argument. Terry Reedy <tjreedy@udel.edu> - 2014-03-17 18:06 -0400
Re: 'complex' function with string argument. Skip Montanaro <skip@pobox.com> - 2014-03-17 18:59 -0500
Re: 'complex' function with string argument. Chris Angelico <rosuav@gmail.com> - 2014-03-18 11:16 +1100
Re: 'complex' function with string argument. Skip Montanaro <skip@pobox.com> - 2014-03-17 20:07 -0500
Re: 'complex' function with string argument. Christian Gollwitzer <auriocus@gmx.de> - 2014-03-18 08:04 +0100
Re: 'complex' function with string argument. Chris Angelico <rosuav@gmail.com> - 2014-03-18 18:11 +1100
Re: 'complex' function with string argument. Steven D'Aprano <steve@pearwood.info> - 2014-03-18 08:00 +0000
Re: 'complex' function with string argument. Christian Gollwitzer <auriocus@gmx.de> - 2014-03-18 09:21 +0100
Re: 'complex' function with string argument. Marko Rauhamaa <marko@pacujo.net> - 2014-03-18 16:00 +0200
Page 1 of 2 [1] 2 Next page →
| From | Jayanth Koushik <jnkoushik@gmail.com> |
|---|---|
| Date | 2014-03-15 09:26 -0700 |
| Subject | 'complex' function with string argument. |
| Message-ID | <8c862bec-815e-424c-81e2-8f37ebab1c35@googlegroups.com> |
Hi everyone!
This is regarding the inbuilt 'complex' function. The python docs say:
"Note: When converting from a string, the string must not contain whitespace around the central + or - operator. For example, complex('1+2j') is fine, but complex('1 + 2j') raises ValueError."
Why is this so? Why can't spaces be allowed everywhere and simply ignored? I went through the source and it did not seem like this was an internal requirement, so it seems like a design choice. Is there any reason why spaces in the middle would be a problem?
Jayanth Koushik
[toc] | [next] | [standalone]
| From | Mark H Harris <harrismh777@gmail.com> |
|---|---|
| Date | 2014-03-17 11:18 -0500 |
| Message-ID | <lg779d$5f4$2@speranza.aioe.org> |
| In reply to | #68367 |
On 3/15/14 11:26 AM, Jayanth Koushik wrote:
This is a very interesting philosophical question, one which I am
surprised no one has answered; although, I think the reason for that
might be entirely obvious.
You actually answered your own question, as you were asking it. If the
doc says "whatever you do, don't push the purple button," well, leave
the purple button alone. :) (I don't know, push it if you want)
If you monitor the PEP process, or have ever taken part in python-ideas,
or python-dev (either directly, or just lurking) you will notice that
python is developed through a very interesting active committee process
(that is really something phenomenal; cool community).
How should one spell a complex number? Should we use i or j ? Should the
imaginary part be set off somehow? Should literals be parsed
differently (or consistently) with correctly formed strings? Who knows,
beats me.
consider:
>>> complex( 3 + 2 j)
SyntaxError: invalid syntax
>>> complex( 3 +2j )
(3+2j)
>>>
I don't know... you tell me.
>>> complex('3+2j')
(3+2j)
>>> complex('3 +2j')
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
complex('3 +2j')
ValueError: complex() arg is a malformed string
>>>
Again, beats me. I just don't know.
But I do know that the spelling book says, Do it this way:
complex('3+2j').
Seems simple enough.
Philosophically, I tend to think about it this way. A complex number is
like any other number. I would not form a PI string like this> ' 3 .14 1
5 9265 3 . . .' I would rather see it formed like so, '3.1415926535'
This '3 + 2j' is not a number, its an algebraic sum.
This '3+2j' is a complex number. Ok, maybe not, but its closer to
what we expect (I'm sorry, but I like i instead of j )
Also, philosophically, C ignores white space; python does not.
I agree with this now; before I did not. White space is just as much a
part of how interpretation occurs, within symbol processing/parsing.
Some choices are arbitrary, some are community concurrence (PEPs), some
are philosophical, and most are just convenient intuition.
My Greek professor used to say, "there is no 'why' in Greek".
Python is similar.
Cheers
[toc] | [prev] | [next] | [standalone]
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Date | 2014-03-18 04:03 +1100 |
| Message-ID | <mailman.8201.1395075805.18130.python-list@python.org> |
| In reply to | #68431 |
On Tue, Mar 18, 2014 at 3:18 AM, Mark H Harris <harrismh777@gmail.com> wrote:
> You actually answered your own question, as you were asking it. If the doc
> says "whatever you do, don't push the purple button," well, leave the purple
> button alone. :) (I don't know, push it if you want)
https://www.wizards.com/magic/magazine/article.aspx?x=mtg/daily/mm/69
> If you monitor the PEP process, or have ever taken part in python-ideas, or
> python-dev (either directly, or just lurking) you will notice that python is
> developed through a very interesting active committee process (that is
> really something phenomenal; cool community).
Not really a committee, more of a champion-and-bikeshedders approach -
often with more than one level of champion, as when a PEP has an
author (the first champion) and either the BDFL or his delegate (the
second champion, whose role is usually just to say yay or nay). It's a
curious process, but one that works fairly well.
> How should one spell a complex number? Should we use i or j ? Should the
> imaginary part be set off somehow? Should literals be parsed differently
> (or consistently) with correctly formed strings? Who knows, beats me.
>
> consider:
>>>> complex( 3 + 2 j)
> SyntaxError: invalid syntax
>>>> complex( 3 +2j )
> (3+2j)
>>>>
> I don't know... you tell me.
That's for the sake of parsing clarity. (Incidentally, the call to
complex() is redundant in each case.) Everything in Python consists of
tokens - those tokens, in your examples, are:
"complex", "(", whitespace, "3", whitespace, "+", whitespace, "2",
whitespace, "j", ")", end of line
and
"complex", "(", whitespace, "3", whitespace, "+", "2j", whitespace,
")", end of line
In the first case, the parser then has two symbol-type tokens ("2" and
"j") separated by whitespace, with no operator. That's a problem. Did
you mean "2+j", or "2==j", etc? Since j is perfectly natural as a
name, it's going to be interpreted that way.
In the second case, that translates into a perfectly valid parse tree,
because "2j" is an imaginary literal.
>>> ast.dump(ast.parse("complex( 3 +2j )"))
"Module(body=[Expr(value=Call(func=Name(id='complex', ctx=Load()),
args=[BinOp(left=Num(n=3), op=Add(), right=Num(n=2j))], keywords=[],
starargs=None, kwargs=None))])"
The sole argument to complex() is an expression which sums the integer
3 and the imaginary 2j, which results in the complex (3+2j), which
complex() looks at and returns unchanged. And that's what you see.
>>>> complex('3+2j')
> (3+2j)
>>>> complex('3 +2j')
> Traceback (most recent call last):
> File "<pyshell#17>", line 1, in <module>
> complex('3 +2j')
> ValueError: complex() arg is a malformed string
>>>>
>
> Again, beats me. I just don't know.
And now what you're looking at is the construction of a complex from a
string. Now, instead of going by the rules of the Python lexer, it
goes by the rules of the complex constructor. You can't use extra
spaces there. You could, of course, write your own function that
parses whatever format you like (including the use of i instead of j),
or you can use ast.literal_eval to parse a string based on Python's
lexing, but with complex(str) you follow the rules of complex(str).
> Philosophically, I tend to think about it this way. A complex number is like
> any other number. I would not form a PI string like this> ' 3 .14 1 5 9265 3
> . . .' I would rather see it formed like so, '3.1415926535'
Right.
> This '3 + 2j' is not a number, its an algebraic sum.
>
> This '3+2j' is a complex number. Ok, maybe not, but its closer to what we
> expect (I'm sorry, but I like i instead of j )
Hmm. That's a pretty tricky distinction. In Python source code, those
two are identical, and they're both rendered as a sum. (Lexically. The
CPython optimizer, and presumably other Pythons' optimizers, will
notice at compile time that you're adding two literals, and store the
sum. But as you see from the AST above, it's the sum of two values.)
It's actually not possible, as far as I know, to truly represent a
complex number; all you can do is represent the sum of a real part and
an imaginary part.
> Also, philosophically, C ignores white space; python does not.
That's not really anything to do with it. The two languages'
approaches to whitespace inside expressions are identical, save that
Python will only allow newlines if the expression is "clearly
unfinished", eg if it has unbalanced open parens. Horizontal
whitespace is fine in both languages. (Of course, C doesn't even
_have_ a complex literal notation, so the distinction is slightly
moot.)
ChrisA
[toc] | [prev] | [next] | [standalone]
| From | Marko Rauhamaa <marko@pacujo.net> |
|---|---|
| Date | 2014-03-17 20:15 +0200 |
| Message-ID | <87y508r8ro.fsf@elektro.pacujo.net> |
| In reply to | #68434 |
Chris Angelico <rosuav@gmail.com>:
> On Tue, Mar 18, 2014 at 3:18 AM, Mark H Harris <harrismh777@gmail.com> wrote:
>> Philosophically, I tend to think about it this way. A complex number
>> is like any other number. I would not form a PI string like this> ' 3
>> .14 1 5 9265 3 . . .' I would rather see it formed like so,
>> '3.1415926535'
>
> Right.
Well, Java 7 allows you to embed underscores freely in numeric literals.
Would be a nice addition to Python as well:
if unit == 'G':
count *= 1_000_000_000
vs:
if unit == 'G':
count *= 1000000000
>> This '3 + 2j' is not a number, its an algebraic sum.
>>
>> This '3+2j' is a complex number. Ok, maybe not, but its closer to what
>> we expect (I'm sorry, but I like i instead of j )
>
>Hmm. That's a pretty tricky distinction.
Is "-2.0" a literal?
What's the outcome of
-2.0.__str__()
Marko
[toc] | [prev] | [next] | [standalone]
| From | Ian Kelly <ian.g.kelly@gmail.com> |
|---|---|
| Date | 2014-03-17 12:28 -0600 |
| Message-ID | <mailman.8216.1395080937.18130.python-list@python.org> |
| In reply to | #68448 |
On Mon, Mar 17, 2014 at 12:15 PM, Marko Rauhamaa <marko@pacujo.net> wrote: > Is "-2.0" a literal? > > What's the outcome of > > -2.0.__str__() No. The compiler will try to optimize it into a single constant if it can, but it has to be done in accordance with the order of operations. In that example, the __str__ method is called before the unary - is applied, resulting in an error.
[toc] | [prev] | [next] | [standalone]
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Date | 2014-03-18 05:59 +1100 |
| Message-ID | <mailman.8218.1395082794.18130.python-list@python.org> |
| In reply to | #68448 |
On Tue, Mar 18, 2014 at 5:15 AM, Marko Rauhamaa <marko@pacujo.net> wrote:
>>> This '3 + 2j' is not a number, its an algebraic sum.
>>>
>>> This '3+2j' is a complex number. Ok, maybe not, but its closer to what
>>> we expect (I'm sorry, but I like i instead of j )
>>
>>Hmm. That's a pretty tricky distinction.
>
> Is "-2.0" a literal?
>
> What's the outcome of
>
> -2.0.__str__()
If you mean (-2.0).__str__(), then it returns '-2.0', but that proves
nothing. Lots of objects have a str() which isn't a literal. Closer to
what you're talking about would be repr(), but even then, it doesn't
prove that something's a literal. The easiest way to tell is probably
ast.parse():
>>> ast.dump(ast.parse("-2.0"))
'Module(body=[Expr(value=UnaryOp(op=USub(), operand=Num(n=2.0)))])'
It's an expression consisting of unary minus and the float literal 2.0.
ChrisA
[toc] | [prev] | [next] | [standalone]
| From | Marko Rauhamaa <marko@pacujo.net> |
|---|---|
| Date | 2014-03-17 21:22 +0200 |
| Message-ID | <87siqgr5p1.fsf@elektro.pacujo.net> |
| In reply to | #68453 |
Chris Angelico <rosuav@gmail.com>: > On Tue, Mar 18, 2014 at 5:15 AM, Marko Rauhamaa <marko@pacujo.net> wrote: >> Is "-2.0" a literal? >> >> What's the outcome of >> >> -2.0.__str__() > > If you mean (-2.0).__str__(), then it returns '-2.0', but that proves > nothing. The point is, you don't need to "philosophize" about complex literals when even negative numbers don't have literals in Python. Marko
[toc] | [prev] | [next] | [standalone]
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Date | 2014-03-18 06:32 +1100 |
| Message-ID | <mailman.8219.1395084747.18130.python-list@python.org> |
| In reply to | #68455 |
On Tue, Mar 18, 2014 at 6:22 AM, Marko Rauhamaa <marko@pacujo.net> wrote:
> Chris Angelico <rosuav@gmail.com>:
>
>> On Tue, Mar 18, 2014 at 5:15 AM, Marko Rauhamaa <marko@pacujo.net> wrote:
>>> Is "-2.0" a literal?
>>>
>>> What's the outcome of
>>>
>>> -2.0.__str__()
>>
>> If you mean (-2.0).__str__(), then it returns '-2.0', but that proves
>> nothing.
>
> The point is, you don't need to "philosophize" about complex literals
> when even negative numbers don't have literals in Python.
Ah! I get you.
The difference between literals and constants is one that almost never
matters, though. Python may not have a syntax for negative or complex
literals, but it does have notations for various sorts of constants,
which function the same way. (Literals are by definition constants.)
So Python may not have a convenient notation for "number of seconds in
a week" (unless you work with DNS and find the bare integer 604800
convenient), but you can write 7*24*60*60 and it's just as good in a
function:
>>> ast.dump(ast.parse("7*24*60*60"))
'Module(body=[Expr(value=BinOp(left=BinOp(left=BinOp(left=Num(n=7),
op=Mult(), right=Num(n=24)), op=Mult(), right=Num(n=60)), op=Mult(),
right=Num(n=60)))])'
>>> def f(x):
return x + 7*24*60*60
>>> dis.dis(f)
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 6 (604800)
6 BINARY_ADD
7 RETURN_VALUE
There's absolutely no run-time cost to writing it out, and you get to
be flexible with whitespace and such, which you can't do with
literals.
ChrisA
[toc] | [prev] | [next] | [standalone]
| From | Steven D'Aprano <steve@pearwood.info> |
|---|---|
| Date | 2014-03-18 04:08 +0000 |
| Message-ID | <5327c6ab$0$2923$c3e8da3$76491128@news.astraweb.com> |
| In reply to | #68455 |
On Mon, 17 Mar 2014 21:22:18 +0200, Marko Rauhamaa wrote:
> Chris Angelico <rosuav@gmail.com>:
>
>> On Tue, Mar 18, 2014 at 5:15 AM, Marko Rauhamaa <marko@pacujo.net>
>> wrote:
>>> Is "-2.0" a literal?
>>>
>>> What's the outcome of
>>>
>>> -2.0.__str__()
>>
>> If you mean (-2.0).__str__(), then it returns '-2.0', but that proves
>> nothing.
>
> The point is, you don't need to "philosophize" about complex literals
> when even negative numbers don't have literals in Python.
But Python *does* have complex (well, imaginary to be precise) literals.
The j suffix to a number makes it complex:
py> type(2j)
<class 'complex'>
Complex numbers with both a real and imaginary component are not treated
as literals:
py> import ast
py> ast.dump(ast.parse("2j"))
'Module(body=[Expr(value=Num(n=2j))])'
py> ast.dump(ast.parse("1+2j"))
'Module(body=[Expr(value=BinOp(left=Num(n=1), op=Add(),
right=Num(n=2j)))])'
and in recent versions, the peephole optimizer optimizes them:
py> from dis import dis
py> dis("1+2j")
1 0 LOAD_CONST 2 ((1+2j))
3 RETURN_VALUE
--
Steven
[toc] | [prev] | [next] | [standalone]
| From | Mark H Harris <harrismh777@gmail.com> |
|---|---|
| Date | 2014-03-17 13:20 -0500 |
| Message-ID | <lg7ee0$qe1$1@speranza.aioe.org> |
| In reply to | #68434 |
On 3/17/14 12:03 PM, Chris Angelico wrote:
>>>> ast.dump(ast.parse("complex( 3 +2j )"))
> "Module(body=[Expr(value=Call(func=Name(id='complex', ctx=Load()),
> args=[BinOp(left=Num(n=3), op=Add(), right=Num(n=2j))], keywords=[],
> starargs=None, kwargs=None))])"
>
> The sole argument to complex() is an expression which sums the integer
> 3 and the imaginary 2j, which results in the complex (3+2j), which
> complex() looks at and returns unchanged. And that's what you see.
~very nice.
Ok, going along with Mark's comment about this bug report:
> See http://bugs.python.org/issue9574
This string '3 +2j' should probably be ok from the complex() string
constructor standpoint, right?
I mean, there might be more than one constructor for string, mighten-it?
marcus
[toc] | [prev] | [next] | [standalone]
| From | Steven D'Aprano <steve@pearwood.info> |
|---|---|
| Date | 2014-03-18 04:52 +0000 |
| Message-ID | <5327d112$0$2923$c3e8da3$76491128@news.astraweb.com> |
| In reply to | #68431 |
On Mon, 17 Mar 2014 11:18:56 -0500, Mark H Harris wrote:
> How should one spell a complex number? Should we use i or j ? Should the
> imaginary part be set off somehow? Should literals be parsed
> differently (or consistently) with correctly formed strings? Who knows,
> beats me.
With respect, that's just because you would make a lousy language
designer :-) The answer to most of those questions should be pretty
obvious, with perhaps just one that isn't clear.
"How should one spell a complex number?" There is perfectly good syntax
for complex numbers used by mathematicians and engineers for over a
century. There is no need to invent something different just for the sake
of being different:
Yes: 2+3i or 2+3j
No: @2|3?
"Should we use i or j ?" There are good reasons for both i and j. This
one comes down to personal preference.
"Should the imaginary part be set off somehow?" What do you mean "set
off"? Why do you want to? Since the imaginary part can appear on its own:
z = 3j
we cannot make "setting off" compulsory. Once you have syntax for complex
numbers with an imaginary component, everything else Just Works with no
additional effort:
z = 2 + 3j # an expression adding 2 to 3j
z = 5*3j # an expression multiplying 5 by 3j
There's no need for dedicated syntax for complex numbers beyond the
simple no-real-part case. You get everything else for free from basic
arithmetic expressions, so there actually isn't need to parse complex
literals beyond the j suffix.
"Should literals be parsed differently (or consistently) with correctly
formed strings?" Once you decide that complex literals should be formed
from only the imaginary part, 3j, parsing literals is simple. So is
passing strings: you have something that looks like a float, with a j
suffix. Obviously they should parse the same.
assert 1.234j == complex('1.234j')
Problem solved.
Well, not quite -- it would be rather limiting if the complex constructor
only accepted complex numbers with an implicitly zero real part. We'd
like to accept anything that repr(z) can print. Since repr(z) prints
complex numbers with a + or - infix operator, the complex constructor
should accept the same inside strings.
How flexible should the complex constructor be? Should it bend over
backwards to accept any mathematical expression that includes a complex j
suffix, e.g. complex("2**3i")? I think not, since complex numbers don't
display like that. Our only obligation is to parse the strings that
complex.__repr__ can produce, not to parse any imaginable numeric
expression.
So at a minimum, complex should accept strings that look like
<float>j
<float>+<float>j
<float>-<float>j
For the same reason that float("2") works, we should also allow strings
that look like:
<float>
with no j suffix. Anything else, including spaces around the + and -
symbols, would be a bonus.
> consider:
> >>> complex( 3 + 2 j)
> SyntaxError: invalid syntax
That's a syntax error for the same reason that:
x = 1 2
is a syntax error. Nothing to do with the + sign. It's the spaces between
the 2 and the j.
> >>> complex( 3 +2j )
> (3+2j)
> >>>
> I don't know... you tell me.
In both cases, the call to complex is redundant. You've already created a
complex number, using syntax, then you pass it to the complex function
which just returns the same number.
> >>> complex('3+2j')
> (3+2j)
> >>> complex('3 +2j')
> Traceback (most recent call last):
> File "<pyshell#17>", line 1, in <module>
> complex('3 +2j')
> ValueError: complex() arg is a malformed string
Personally, I would like complex to accept spaces around the + or -, as
it already accepts leading and trailing spaces. But it's not a big deal.
[...]
> Also, philosophically, C ignores white space; python does not.
C does not ignore whitespace.
forwhile
is not the same as
for while
The first is a valid identifier, the second is a syntax error. Oh
somebody please tell me it's not a valid C expression! *wink*
--
Steven
[toc] | [prev] | [next] | [standalone]
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Date | 2014-03-18 15:59 +1100 |
| Message-ID | <mailman.8235.1395118800.18130.python-list@python.org> |
| In reply to | #68479 |
On Tue, Mar 18, 2014 at 3:52 PM, Steven D'Aprano <steve@pearwood.info> wrote: > The first is a valid identifier, the second is a syntax error. Oh > somebody please tell me it's not a valid C expression! *wink* It's not a valid C expression. ChrisA
[toc] | [prev] | [next] | [standalone]
| From | Mark H Harris <harrismh777@gmail.com> |
|---|---|
| Date | 2014-03-18 11:14 -0500 |
| Message-ID | <lg9rdm$us9$1@speranza.aioe.org> |
| In reply to | #68479 |
On 3/17/14 11:52 PM, Steven D'Aprano wrote:
> On Mon, 17 Mar 2014 11:18:56 -0500, Mark H Harris wrote:
>> Who knows, beats me.
> With respect, that's just because you would make a lousy language
> designer :-)
Ouch ;-)
> "How should one spell a complex number?" There is perfectly good syntax
> for complex numbers used by mathematicians and engineers for over a
> century. There is no need to invent something different just for the sake
> of being different:
> Yes: 2+3i or 2+3j
Yes. my Q was rhetorical only. And for the sake of discussion,
particularly on the part of the OP, to think about what one expects
based on experience and common sense, as a mathematician. (that doesn't
mean it will be easy for the lexical parser.
> "Should we use i or j ?" There are good reasons for both i and j. This
> one comes down to personal preference.
no, not really. nobody writes, e^(jPI) + 1 = 0
Euler wants to see e^(iPI) + 1 = 0 ;-)
> "Should the imaginary part be set off somehow?" What do you mean "set
> off"? Why do you want to? Since the imaginary part can appear on its own:
simply, is 2j a literal complex part? ...yes 2 j ...no
In other words, there must NEVER be a space between the 2 and j.
This is debatable: 3 +2j although, I want to see 3+2j
> z = 2 + 3j # an expression adding 2 to 3j
> z = 5*3j # an expression multiplying 5 by 3j
all good, well until its not
> How flexible should the complex constructor be? Should it bend over
> backwards to accept any mathematical expression that includes a complex j
> suffix, e.g. complex("2**3i")? I think not,
I think not either. But, it is possible to have *many* constructors/
But, really, how often is this a problem? like almost never!
>> >>> complex( 3 +2j )
>> (3+2j)
>> >>>
>> I don't know... you tell me.
>
> In both cases, the call to complex is redundant. You've already created a
> complex number, using syntax, then you pass it to the complex function
> which just returns the same number.
Of course. I was merely pointing out that the constructor for
'literals' (whatever you guys mean by that) is 'different' than the
consistency with the string constructor. As Chris pointed out these are
two markedly different animals; one is a valid parse syntax, the other
is a string constructor. But here is my point--- to the user the
difference comes down to semantics, which is not really true.
cf. below
>> >>> complex('3+2j')
>> (3+2j)
>> >>> complex('3 +2j')
>> Traceback (most recent call last):
>> File "<pyshell#17>", line 1, in<module>
>> complex('3 +2j')
>> ValueError: complex() arg is a malformed string
>> Also, philosophically, C ignores white space; python does not.
This was said tongue in cheek... *both* languages inconsistently
observer (and ignore) white space! But, in general, white space is more
important to python, and less important to C.
I'm still hung up on whether I'm a lousy language designer. I guess
we'll know if people use my language (or not)! I suppose they might use
it even though its lousy; on the other hand, it might be too simple for
folks to be able to figure it out. :)
marcus
[toc] | [prev] | [next] | [standalone]
| From | wxjmfauth@gmail.com |
|---|---|
| Date | 2014-03-19 00:30 -0700 |
| Message-ID | <11b58171-a99b-4ddf-8e6c-7b4f3169c60c@googlegroups.com> |
| In reply to | #68506 |
z = a + b*i with a, b, elements of R z = r*exp(i*phi) with r, phi, elements of R z = [[a, -b], [b, a]] with a, b, elements of R This is, in my mind, more questionable: >>> complex(2, 1+1j) (1+1j) >>> >>> print(complex.__doc__) complex(real[, imag]) -> complex number Create a complex number from a real part and an optional imaginary part. This is equivalent to (real + imag*1j) where imag defaults to 0. jmf
[toc] | [prev] | [next] | [standalone]
| From | Marko Rauhamaa <marko@pacujo.net> |
|---|---|
| Date | 2014-03-19 10:51 +0200 |
| Message-ID | <87lhw6po53.fsf@elektro.pacujo.net> |
| In reply to | #68538 |
wxjmfauth@gmail.com: > This is, in my mind, more questionable: > >>>> complex(2, 1+1j) > (1+1j) I find it neat, actually. Marko
[toc] | [prev] | [next] | [standalone]
| From | wxjmfauth@gmail.com |
|---|---|
| Date | 2014-03-19 02:52 -0700 |
| Message-ID | <d1f09443-f5d4-4ed6-880f-bc15810a1fdd@googlegroups.com> |
| In reply to | #68540 |
Le mercredi 19 mars 2014 09:51:20 UTC+1, Marko Rauhamaa a écrit : > wxjmfauth@gmail.com: > > > > > This is, in my mind, more questionable: > > > > > >>>> complex(2, 1+1j) > > > (1+1j) > > > > I find it neat, actually. > > > > > > Marko >>> # tricky: yes, neat: no >>> complex(1+1j, 2) (1+3j) >>>
[toc] | [prev] | [next] | [standalone]
| From | Marko Rauhamaa <marko@pacujo.net> |
|---|---|
| Date | 2014-03-19 12:09 +0200 |
| Message-ID | <87bnx233gd.fsf@elektro.pacujo.net> |
| In reply to | #68543 |
wxjmfauth@gmail.com: > Le mercredi 19 mars 2014 09:51:20 UTC+1, Marko Rauhamaa a écrit : >> wxjmfauth@gmail.com: >> >>>> complex(2, 1+1j) >> > (1+1j) >> >> I find it neat, actually. > >>>> # tricky: yes, neat: no >>>> complex(1+1j, 2) > (1+3j) So complex(a, b) is documented to produce a+bj when a and b are integers or floats. What's more natural than saying it produces a+bj when a and b are complex numbers? It's a straightforward generalization that in no way violates the more limited documentation. Marko
[toc] | [prev] | [next] | [standalone]
| From | Ian Kelly <ian.g.kelly@gmail.com> |
|---|---|
| Date | 2014-03-19 04:33 -0600 |
| Message-ID | <mailman.8276.1395225264.18130.python-list@python.org> |
| In reply to | #68544 |
On Wed, Mar 19, 2014 at 4:09 AM, Marko Rauhamaa <marko@pacujo.net> wrote: > wxjmfauth@gmail.com: > >> Le mercredi 19 mars 2014 09:51:20 UTC+1, Marko Rauhamaa a écrit : >>> wxjmfauth@gmail.com: >>> >>>> complex(2, 1+1j) >>> > (1+1j) >>> >>> I find it neat, actually. >> >>>>> # tricky: yes, neat: no >>>>> complex(1+1j, 2) >> (1+3j) > > So complex(a, b) is documented to produce a+bj when a and b are integers > or floats. What's more natural than saying it produces a+bj when a and b > are complex numbers? It's a straightforward generalization that in no > way violates the more limited documentation. When is it ever useful though? I only see a use for passing a as complex if b is omitted, and I don't see any use for passing b as complex. If there's no use case, then it's just a confusing edge case that will catch unsuspecting programmers who thought the data they were passing in was real-valued when actually it wasn't. It would be better to raise an exception in either of the cases above, in my opinion. If you really want to form a complex a+bj from two other complex numbers, there is always the explicit (a + b * 1j). That said, complex numbers have been around since 1.4 or so, and there's probably not much chance to change it now.
[toc] | [prev] | [next] | [standalone]
| From | Marko Rauhamaa <marko@pacujo.net> |
|---|---|
| Date | 2014-03-19 12:53 +0200 |
| Message-ID | <877g7q31f7.fsf@elektro.pacujo.net> |
| In reply to | #68546 |
Ian Kelly <ian.g.kelly@gmail.com>: > On Wed, Mar 19, 2014 at 4:09 AM, Marko Rauhamaa <marko@pacujo.net> wrote: >> So complex(a, b) is documented to produce a+bj when a and b are integers >> or floats. What's more natural than saying it produces a+bj when a and b >> are complex numbers? It's a straightforward generalization that in no >> way violates the more limited documentation. > > When is it ever useful though? [...] It would be better to raise an > exception in either of the cases above, in my opinion. I don't think it matters one way or another. Medieval mathematicians had to address an analogous issue when they had to decide if x + 0 was meaningful. After all, adding nothing doesn't make any sense and should raise a ValueError exception... Marko
[toc] | [prev] | [next] | [standalone]
| From | Ian Kelly <ian.g.kelly@gmail.com> |
|---|---|
| Date | 2014-03-19 13:35 -0600 |
| Message-ID | <mailman.8285.1395257751.18130.python-list@python.org> |
| In reply to | #68547 |
On Wed, Mar 19, 2014 at 4:53 AM, Marko Rauhamaa <marko@pacujo.net> wrote:
> Ian Kelly <ian.g.kelly@gmail.com>:
>
>> On Wed, Mar 19, 2014 at 4:09 AM, Marko Rauhamaa <marko@pacujo.net> wrote:
>>> So complex(a, b) is documented to produce a+bj when a and b are integers
>>> or floats. What's more natural than saying it produces a+bj when a and b
>>> are complex numbers? It's a straightforward generalization that in no
>>> way violates the more limited documentation.
>>
>> When is it ever useful though? [...] It would be better to raise an
>> exception in either of the cases above, in my opinion.
>
> I don't think it matters one way or another.
>
> Medieval mathematicians had to address an analogous issue when they had
> to decide if
>
> x + 0
>
> was meaningful. After all, adding nothing doesn't make any sense and
> should raise a ValueError exception...
I wasn't aware that algebra had ValueErrors. Describing an operation
as "undefined" isn't the same thing. Anyway, if mathematicians
discover that the definitions of the past were flawed or incomplete,
then they redefine them. Case in point, if we were still using
Brahmagupta's rules for zero, then 0/0 would be 0.
Python though has backward compatibility to worry about. Because of
this, it is much simpler to add wanted behavior than to remove
unwanted behavior. If an operation can be generalized but the
generalization has no apparent use case, it *may* be better to
disallow it, with the possibility of adding it later when a user pops
up and says "Hey, this would actually be useful to me", than to allow
it from the beginning, and then have no option to remove it later when
it turns out to be merely a nuisance.
Compare for example the 2-argument int constructor. Normally this is
meant to be called like int("42", 13), where it will interpret the
digits passed as base 13 and return 54. We might generalize that and
say that if the user passes int(42, 13), it should also return 54,
seeing that the repr of 42 provides the digits "42". It is more
likely though that this call merely indicates a bug in the user's
code, and fortunately in this case what Python actually does is to
raise a TypeError.
Anyway, curious though this tangent is, further discussion is unlikely
to produce any useful outcome, so I'll just leave it there.
[toc] | [prev] | [next] | [standalone]
Page 1 of 2 [1] 2 Next page →
Back to top | Article view | comp.lang.python
csiph-web