Tanner Burton
Tanner Burton

Reputation: 143

Python numpy arrays staying integers

I'm currently taking a numerical methods class and wrote a function to carry out Gauss Elimination. I noticed that for some reason when carrying out operations on a numpy array, python fails to convert integers into floats. so I'm getting zeros instead of a float. Here is the segment of the code that carries out the Gauss Elimination

for k in range(h - 1):
        p = k
        B = a[k, k]
        for i in range(k+1, l):
            if a[i, k] > B:
                B = a[i, k]
                p = i

        if p != k:
            a[[k, p]] = a[[p, k]]
            b[[k, p]] = b[[p, k]] 

        for i in range(k+1, l):
            s = a[i, k] / a[k, k]
            for g in range(l):
                a[i, g] = a[i, g] - s * a[k, g]
            
            b[i, 0] = b[i, 0] - s * b[k, 0]

Here is the input used when calling the function:

a = np.array([[8, 4, -1], [-2, 5, 1], [2, -1, 6]])
b = np.array([[11], [4], [7]])
print(GaussElim(a, b)[4])

Any Idea why this may be happening? I can circumvent the problem by just writing my inputs as floats, but I'd like to avoid that if possible. I'm running Python 3.9.7 on the latest version of VS Code. I am using numpy arrays for my input matrices if that affects anything.

**Note: What I noticed was that the array elements are staying an integer and not being converted to floats when operated on. Changing my inputs into the numpy array to start as floats solves the issue, but I'd like to not have to write ".0" at the end of every input for cleanliness.

Upvotes: 1

Views: 1732

Answers (1)

ATony
ATony

Reputation: 703

I believe that Python is doing the operations as floats but since the arrays are dtype=int64, they are being cast back to integers in order to store them.

As @Ynjxsjmh comment mentions, you can explicitly set the dtype of the arrays to float at specification:

a = np.array([[8, 4, -1], [-2, 5, 1], [2, -1, 6]], dtype='float64')
b = np.array([[11], [4], [7]], dtype='float64')

Alternatively, since all elements in an array have the same type, you can just force it by adding a point to one of the numbers:

a = np.array([[8., 4, -1], [-2, 5, 1], [2, -1, 6]])
b = np.array([[11.], [4], [7]])

Upvotes: 1

Related Questions