Reputation: 356
I built a calculator for a bio equation, and I think I've narrowed down the source of my problem, which is a natural log I take:
goldman = ((R * T) / F) * cmath.log(float(top_row) / float(bot_row))
print("Membrane potential: " + str(goldman) + "V"
My problem is that it will only display the output in a complex form:
Membrane potential: (0.005100608207126714+0j)V
Is there any way of getting this to print as a floating number? Nothing I've tried has worked.
Upvotes: 18
Views: 57121
Reputation: 1
It is simple if you need only real part of the complex number.
goldman = 0.005100608207126714+0j
print(goldman)
(0.005100608207126714+0j)
goldman = float(goldman.real)
print(goldman)
0.005100608207126714
If you need absolute value then use following
goldman = 0.005100608207126714+0j
print(goldman)
(0.005100608207126714+0j)
goldman = float(abs(goldman))
print(goldman)
0.005100608207126714
print(type(goldman))
<class 'float'>
Upvotes: 0
Reputation: 21
If you want to just convert it to float value you can do this:
def print_float(x1):
a=x1.real
b=x1.imag
val=a+b
print(val)
ec=complex(2,3)
In this way you can actually get the floating value.
Upvotes: 2
Reputation: 69182
Use math.log
instead of cmath.log
.
Since you don't want the imaginary part of the result, it would be better to use math.log
instead of cmath.log
. This way, you'll get an error if your input is not in the valid domain for a real log
, which is much better than silently giving you meaningless results (for example, if top_row
is negative). Also, complex numbered results make no sense for this particular equation.
ie, use:
goldman = ((R * T) / F) * math.log(float(top_row) / float(bot_row))
Upvotes: 7
Reputation: 309919
Complex numbers have a real part and an imaginary part:
>>> c = complex(1, 0)
>>> c
(1+0j)
>>> c.real
1.0
It looks like you just want the real part... so:
print("Membrane potential: " + str(goldman.real) + "V"
Upvotes: 22