How do you insert complex numbers in Python?

Asked

Viewed 3,288 times

4

I already know when inserting one int in the print it is necessary to put the %i. To the float is %f and to the string is %s. Now how do I insert boolean and complex? The bool and the complex?

1 answer

2


Boolean

No format specifier for bool. You can print it using some of the existing specifiers for printing integral 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, it is possible to call the method __format__ to build everything on 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 too.

From Python 2.6, you can define as the objects of your own classes to respond to sequences of formats. Thus, 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 occupy more space and operate more slowly

Browser other questions tagged

You are not signed in. Login or sign up in order to post.