Shlomi Elhaiani
Shlomi Elhaiani

Reputation: 21

How to define a float matrix in python 2.7

I am trying to define a float matrix using this code in python 2.7:

import numpy as np
A=np.array([[1/16,1/8,1/16],[1/8,1/4,1/8]])
print A

The result matrix is a floor value matrix (int value matrix):

[[0 0 0]
[0 0 0]]

How can I fix it to a float martix?

Thanks :)

Upvotes: 0

Views: 5016

Answers (2)

cheersmate
cheersmate

Reputation: 2656

As Some programmer dude pointed out, the error lies in your definition of the matrix: Python < 3 performs integer division, so numpy correctly assumes the data type is int and creates an int array.

Besides fixing that by replacing 1/16 with 1./16., you can always force numpy to use a certain data type:

A = np.array([0, 1, True], dtype=float)

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409176

The expression 1/16 is an integer expression. You divide the integer 1 with the integer 16, resulting in the integer 0.

Use floating-point values instead, like 1.0 / 16.0.

Upvotes: 1

Related Questions