How do you insert complex numbers in Python?

3

I already know that when entering a int in print it is necessary to put %i . For the float it is %f and for the string it is %s . Now how do I insert booleans and complexes? The bool and complex ?

    
asked by anonymous 07.05.2015 / 22:32

1 answer

2

Boolean

There is no format specifier for bool . You can print it using some of the existing specifiers to print full types or do something different:

Example 1

 printf("%s", x?"true":"false");

Example 2:

 #define btoa(x) ((x)?"true":"false")

 bool x = true;
 printf("%s\n", btoa(x));

Example 3

 _Bool B = 1;
 printf ("%d\n",b);

Complex

A basic example:

>>> n = 3.4 + 2.3j
>>> print '%05f %05fi' % (n.real, n.imag) // parte real e parte imaginária
3.400000 2.300000i

In addition, you can call the __format__ method to build everything into numeric types directly. Here is an example:

>>> i = -3 # int
>>> l = -33L # long (só em Python 2.X)
>>> f = -10./3 # float
>>> c = - 1./9 - 2.j/9 # complex
>>> [ x.__format__('.3f') for x in (i, l, f, c)]
['-3.000', '-33.000', '-3.333', '-0.111-0.222j']

Note that this works well with negative imaginary parts as well.

From Python 2.6, you can define as the objects of your own classes to respond to sequences of formats. So you can define a subclass complex that can be formatted. Here is an example:

>>> class Complex_formatted(complex):
...     def __format__(self, fmt):
...         cfmt = "({:" + fmt + "}{:+" + fmt + "}j)"
...         return cfmt.format(self.real, self.imag)
... 
>>> z1 = Complex_formatted(.123456789 + 123.456789j)
>>> z2 = Complex_formatted(.123456789 - 123.456789j)
>>> "Meus números complexos são {:0.5f} e {:0.5f}.".format(z1, z2)
'Meus números complexos são (0.12346+123.45679j) e (0.12346-123.45679j).'
>>> "Meus números complexos são {:0.6f} e {:0.6f}.".format(z1, z2)
'Meus números complexos são (0.123457+123.456789j) e (0.123457-123.456789j).'

Objects in this class behave exactly like complex numbers except that they take up more space and operate more slowly

    
08.05.2015 / 04:25