user3015347
user3015347

Reputation: 513

Python integer and float multiplication error

The question seems dummy, but I cannot get it right. The output cm1 is expected to be floats, but I only get zeros and ones.

import numpy as np
import scipy.spatial.distance
sim  = scipy.spatial.distance.cosine
a = [2, 3, 1]
b = [3, 1, 2]
c = [1, 2, 6]
cm0 = np.array([a,b,c])
ca, cb, cc = 0.9, 0.7, 0.4 
cr = np.array([ca, cb, cc])
cm1 = np.empty_like(cm0)
for i in range(3):
    for j in range(3):
        cm1[i,j] = cm0[i,j] * cr[i] * cr[j]
print(cm1)

And I get:

[[1 1 0]
 [1 0 0]
 [0 0 0]]

Upvotes: 0

Views: 390

Answers (2)

Andy Sukowski-Bang
Andy Sukowski-Bang

Reputation: 1420

empty_like() matches the type of the given numpy array by default, as hpaulj suggested in the comments. In your case cm0 is of type integer.

The empty_like function accepts multiple arguments though, one of wich is dtype. Setting dtype to float should solve the problem:

cm1 = np.empty_like(cm0, dtype=float)

And also Python truncates floating point numbers at the decimal point when converting to integers. In your case, every multiplication done results in a number between 1.89 and 0.36, so flooring the results will result in 0s and 1s respectively.

Upvotes: 1

Pablo C
Pablo C

Reputation: 4761

As @hpaulj said in the comments section, the problem is using empty_like which will keep the cm0 dtype, to solve it try:

cm1 = np.empty_like(cm0, dtype=float)

Upvotes: 1

Related Questions