简体   繁体   中英

Python mathematical expression evaluation

I was trying to solve a random problem, I used a relation that I made, when I've come to implement it in python it give me different results than the one that I calculated, so I tried to change.

the thing is I don't get how does python see each one?!?

  • those two expressions here give different results sometimes:

在此处输入图像描述

  • Here's an example:
rows, columns = 4, 4

for row in range(2, rows+1):
    for column in range(1, columns+1):
        print('*'*15)
        result = ((column+1)//2) * ((row+1)//2)
        f_result = (column+1)//2 * (row+1)//2

        print('>> normal expression:', (column+1)//2, (row+1)//2)
        print('>> second expression:', ((column+1)//2), ((row+1)//2))
        print('>>               row:', row)
        print('>>            column:', column)
        print('>>           Results:', result, f_result)
    print()

  • The results:

在此处输入图像描述

You need to understand operator precedence first Check out this link this

for the expression

((col+1)//2) * ((row+1)//2) = (col+1)//2 * (row+1)//2

((col+1)//2) * ((row+1)//2) = ((4+1)//2) * ((4+1)//2)
                            = (5//2)*(5//2)
                            = 2 * 2
                            = 4
(col+1)//2 * (row+1)//2 = (4+1)//2 * (4+1)//2
                        = 5//2 * 5//2
                        = 2 * 5//2
                        = 10//2 (as * has higher precedence than //)
                        = 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM