Learning Python, Why isn't this working? [duplicate] - python

This question already has answers here:
floating point equality in Python and in general
(8 answers)
Closed 9 years ago.
I'm learning python and have been trying various things... for some reason this isn't working!
x = (-2.1)
if ( (0.4*(x)) - (0.02*(x)) + (1.396) ) == 0.598:
print "TRUE!"
else:
print "FALSE!"
print ( (0.4*(x)) - (0.02*(x)) + (1.396) )
It prints FALSE! followed by 0.598 obviously the answer is 0.598 so why does'nt the "if" statement work? Thanks!

If you try to print out
(0.38 * x) + 1.396 # note simplified maths and syntax
You will quickly see why:
0.5979999999999999
This is not exactly equal to 0.598, because of the way floating point numbers (float) work. You are better testing these using tolerance:
a = (0.38 * x) + 1.396
if abs(a - 0.598) < 0.0001:

You're confused because python print is using float.__str__, which in turn trims up to 12 digits, so numbers are not what is printed:
>>> ( (0.4*(x)) - (0.02*(x)) + (1.396) ).__str__()
'0.598'
>>> ( (0.4*(x)) - (0.02*(x)) + (1.396) ).__repr__()
'0.5979999999999999'

Related

PyCharm returns incorrect Boolean value when comparing two "and" expressions [duplicate]

This question already has answers here:
Python, effect of parentheses on booleans in print statement
(3 answers)
Closed 1 year ago.
I'm still pretty new to Python and this has got me stumped. I've got three computers all running PyCharm, they all are returning the same incorrect Boolean value. Here is the issue. I've been using PyCharm on both of my PC's and my MacBook Pro, so I don't think that it's a software glitch. I've been studying Automate the Boring Stuff, it asks to input these Boolean expressions:
(4 < 5) and (5 < 6)= True
(4 < 5) and (9 < 6)= False (This returns "True" for some reason)
(1 == 2) or (2 == 2)= True
Basically just showing how the and, or, not operators function.
The expression (4 < 5) and (9 < 6) returns as True every single time (in PyCharm). However, I can open Python, type the exact same expression and it comes back as False, as it should. Has anyone else experienced this? Could I be doing anything wrong?
Actual code:
print( 4 < 5 ) and (5 < 6)
print( 4 < 5) and (9 < 6)
print(1 == 2) or (2 == 2)
The results seems to be as expected for me, using Pycharm - on Windows, however that shouldn't matter in this case.
assert (4 < 5) and (5 < 6)
assert (4 < 5) and (9 < 6) is False
assert (1 == 2) or (2 == 2)
You also mentioned that one particular expression (4 < 5) and (9 < 6) is giving you trouble in Pycharm. Perhaps try running the below code? It seems to work as intended for me in Pycharm with the Run command - though I typically just use a keyboard shortcut for this purpose.
if (4 < 5) and (9 < 6):
print('Something went wrong! Please uninstall Pycharm :-)')
else:
print('All good on the home front!')
Output:
All good on the home front!

What is the Order of evaluation without ()? [duplicate]

This question already has answers here:
BODMAS - python
(4 answers)
How do order of operations go on Python?
(5 answers)
Closed last year.
I don't get why this function returns 2.0.
1+1/2*2
For order of operations, I thought it would be multiplication first, then division, left to right, so 1+1/4 to 1+.25 or maybe even return 2/4 =0.5...
I am really confused how it outputs 2.0.
Thanks in advance! Currently studying for an exam.
As for the multiplication and division, the order is left to right. So here is the division first.
1 + 1 / 2 * 2 = 1 + 0.5 * 2 = 1 + 1 = 2
For the next problem, I think if a == 'A' or 'B' is 2 expressions, a == 'A' and 'B'. I've learned a little about C++, and the 'B' refers 66 in the ASCII, which is not 0, so the expression 'B' is always true. Maybe in python it will be the same.
So the code should be if a == 'A' or a == 'B':
See the stackoverflow post: How do order of operations go on Python?
According to that your math, 1+1/2*2, is as follows:
/ 1 \
ans = 1 + ( --- ) X 2
\ 2 /
= 1 + (0.5 X 2)
= 1 + 1
= 2
Multiplication and division are in the same group and are performed left to right (aggregating the answers from the link I referenced).
Enjoy the ASCII art ¯\_(ツ)_/¯

Is python % operator broken [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Why are floating point numbers inaccurate?
(5 answers)
Closed 2 years ago.
I've written some script to help me out finding if something is divisible by other thing, and it fails with larger numbers:
print(x, d)
90744169766518547761620274468374441720233236940 10
print(x/d)
9.074416976651854e+45
print(x / (x/d))
10.0
print(x % (x/d))
2.535301200456459e+30
Since 10.0 is clearly lacking decimal part I don't undertand why % is giving me this trash output?
Does this do what you expect?
>>> print(x//d)
9074416976651854776162027446837444172023323694
>>> print(x // (x//d))
10
>>> print(x % (x//d))
0
The difference is that / in Python 3 always produces a floating point result, even if the operands are integers. In this it differs from C. If you want integer division you need to use //.

Why is math.pow returning different values than the ** operator? [duplicate]

This question already has answers here:
Exponentials in python: x**y vs math.pow(x, y)
(7 answers)
Closed 3 years ago.
I've been trying to solve this problem:
The cube at the bottom will have a volume of n^3, the cube above will
have volume of (n-1)^3 and so on until the top which will have a
volume of 1^3.
You are given the total volume m of the building. Being given m can
you find the number n of cubes you will have to build?
And this is my code
import math
def find_nb(m):
nb = 1
nb_vol = 0
while True:
nb_vol += math.pow(nb, 3)
if (nb_vol == m):
return nb
elif (nb_vol > m):
return -1
nb += 1
Now, when I try to solve for find_nb(2521115597681328384) it returns -1 when it should in fact return 56352. If I change
nb_vol += math.pow(nb, 3)
to
nb_vol += nb ** 3
Everything works correctly. Why?
math.pow always converts it’s arguments to floats first, which are only approximations.
The ** operator uses integers that can never overflow, which means that it always gives a correct result.

Print numbers in terms of engineering units in Python [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Print number in engineering format
How do I print numbers in scientific notation with powers that are multiples of 3? For example:
1.5e4 --> 15e3
1.27e-8 --> 12.7e-9
2.9855e-11 --> 29.855e-9
I'm looking for a function similar to the ENG button on a calculator. Is there a Python package somewhere that does this?
It appears there isn't such a feature yet (at least in Python 2.7), see: http://bugs.python.org/issue8060
On the page http://bytes.com/topic/python/answers/616948-string-formatting-engineering-notation I found the following solution (which I personally don't like that much, but seems to work):
import math
for exponent in xrange(-10, 11):
flt = 1.23 * math.pow(10, exponent)
l = math.log10(flt)
if l < 0:
l = l - 3
p3 = int(l / 3) * 3
multiplier = flt / pow(10, p3)
print '%e =%fe%d' % (flt, multiplier, p3)
Just adapt it according to your needs.
EDIT:
Please look here, too Print number in engineering format

Categories