Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying boolean with float?

I don't understand the line q.append(p[i] * (hit * pHit + (1-hit) * pMiss)), because the variable hit is a boolean value. That boolean value comes from hit = (Z == world[i])

What's going on there? I only have a basic understanding of Python...

p = [0.2, 0.2, 0.2, 0.2, 0.2]

world = ['green', 'red', 'red', 'green', 'green']
Z = 'red'
pHit = 0.6
pMiss = 0.2

def sense(p, Z):
    q=[]
    for i in range(len(p)):
        hit = (Z == world[i])
        q.append(p[i] * (hit * pHit + (1-hit) * pMiss))
        s = sum(q)
        for i in range(len(p)):
            q[i]=q[i]/s      
    return q

print sense(p,Z)
like image 901
user836087 Avatar asked Nov 11 '12 14:11

user836087


People also ask

Can you multiply booleans?

Multiplication is valid in Boolean algebra, and thankfully it is the same as in real-number algebra: anything multiplied by 0 is 0, and anything multiplied by 1 remains unchanged: This set of equations should also look familiar to you: it is the same pattern found in the truth table for an AND gate.

Can you multiply bool and int in C++?

You can, but you are sacrificing readability.

Can int and float be multiply in Python?

Use the multiplication operator to multiply an integer and a float in Python, e.g. my_int * my_float . The multiplication result will always be of type float . Copied! The first example uses the input() function to get an integer from the user.

Can you multiply by bool C++?

C++ Multiplication of two BooleansYou can multiply two boolean values using multiplication operator. The operator converts false to 0, true to 1 and then performs multiplication operation.


2 Answers

In arithmetic, booleans are treated as integers. True is treated as 1 and False is treated as 0.

>>> True + 1
    2
>>> False * 20
    0
>>> True * 20
    20
like image 92
Tim Avatar answered Oct 24 '22 20:10

Tim


In python, booleans are a subclass of int:

>>> isinstance(True, int)
True

They are basically 1 and 0:

>>> True * 1
1
>>> False * 1
0

See Why is bool a subclass of int?

like image 37
Martijn Pieters Avatar answered Oct 24 '22 19:10

Martijn Pieters