[Python] How to stop converting into complex

Discussão em 'Python' iniciado por Stack, Maio 30, 2025.

  1. Stack

    Stack Membro Participativo

    End of this calculation the result automatically turns into complex type in Python 3.

    $ cat test.py
    #!/usr/bin/python
    curryield =-100.0
    frequency = 2
    coupons = 4
    days_to_next = -4.0
    days_period = 180.0

    part1 = (100.0/((1+curryield/frequency)**(coupons-1+(days_to_next/days_period))))
    print("Part 1:{} type:{}".format(part1,type(part1)))


    I want to keep part1 as float and stop converting into complex type

    When I try this to convert it back to float like this

    part2 = float(part1)
    print("Part 2:{} type:{}".format(part2,type(part2)))


    but it throws an exception

    Traceback (most recent call last): File "./test.py", line 12, in <module>
    part2 = float(part1) TypeError: can't convert complex to float


    I know I can convert only the real part part1.real or imaginary part part1.imag to float but I lose the precision. I want to keep the part1 as float after end of the above calculation.

    Continue reading...

Compartilhe esta Página