Hi Steven,
Am 18.03.14 09:00, schrieb Steven D'Aprano:
On Tue, 18 Mar 2014 08:04:44 +0100, Christian Gollwitzer wrote:
Am 15.03.14 17:26, schrieb Jayanth Koushik:
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."
It's funny that you ask this question exactly now; because I'm currently
implementing a compiler for a small language that understands complex
numbers. As others have explained, the basic issue is the question how
to parse an expression like
1+2i*3
is it "complex(1+2i) times 3"
Putting my mathematician's hat on, I would say *absolutely not*.
or is it sum of 1 and product of complex 2i and 3?
This one. Multiplication has higher precedence than addition, so 1+2i*3
has to be evaluated as 1+(2i*3).
The question was not whether the expression should be interpreted the
first way, I'm sorry for being unclear. The question was how to
implement this in a compiler. Because if you implement complex literals
in the tokenizer, you would end up with the tokens of the first
interpretation. But if you implement as imaginary literals, then your
parse tree for "1+2i" ends up as a sum of a real and an imaginary
literal, instead of a complex literal. This works, but it lets your
parse tree grow and possibly generates inefficient code. The answer I
got here, is to parse it as a sum and let the optimizer combine it back
into a single complex constant.
The same problem arises with unary minus, but it's less annoying because
-(a*b) = (-a)*b.
I admit that my knowledge of compiler construction is limited, and I'm
working on my first real-world application now. Oh, and it's not written
in Python.
Christian
--
https://mail.python.org/mailman/listinfo/python-list