I have an array which I’m doing some calculations on. The array begins as
e = array([[1,2,1,3],
[3,-1,-3,-1],
[2,3,1,4]])
I modify it a bit to convert it to:
array([[ 1, 2, 1, 3],
[ 0, -7, -6, -10],
[ 0, -1, -1, -2]])
Then I run this code on it:
import numpy as np
from fractions import Fraction
def ref(x):
dimension = x.shape
row_counter = 1
first_values = [x[i][row_counter] for i in range(dimension[0])] #gets a list of elements of the column
first_values = [number != 0 for number in first_values] #0 is a pivot element?
if False in first_values:
true_index = first_values.index(True); false_index = first_values.index(False)
if true_index > false_index: #not any more
x[[false_index, true_index]] = x[[true_index, false_index]]
for i in range(row_counter+1,dimension[0]):
multiplier = Fraction(x[row_counter][row_counter], x[i][row_counter])**-1
row1 = multiplier*x[row_counter]
row1 = x[i]-row1
print row1
x[i] = row1
return x
Running this returns:
[0 0 -1/7 -4/7]
array([[ 1, 2, 1, 3],
[ 0, -7, -6, -10],
[ 0, 0, 0, 0]])
So the result should be
array([[ 1, 2, 1, 3],
[ 0, -7, -6, -10],
[ 0, 0, -1/7, -4/7]])
It prints the correct row entry but it doesn’t get added to the array, and a row of zeroes is added instead. Could someone please tell me why? Thanks.
In general,
numpyarrays are homogeneous with specific types. For example:When you set an element or slice specifically, what you add gets coerced to the current
dtype, so:but
You can get upcasting when you’re not acting in-place and so
numpyis going to have to make a copy (i.e. a new object) anyway:In your case, you can get the behaviour you want if you start with a
numpyarray of dtypeobject: