Skip to content
Advertisement

Values in Python lists getting overwritten

I am calculating some values for a certain type of matrix A of varying sizes. Namely the backward error, forward error, condition number, and the error magnification (everything with the infinity norm). My values get calculated and then I am trying to put them into lists, looping through increasing sizes of the matrix A. The problem is that after every loop the values in my lists get overwritten by the current condition number and I don’t understand why. Here is my code.

JavaScript

And here is the output using the forward errors as an example since those are short.

JavaScript

I left all those print statements in there behind comments for testing, that was how I figured out everything was being replaced by the condition number. I suspect it must be some simple Python thing that I’m not getting. I just don’t see why or where everything is being overwritten, it is so strange to me. Thank you for reading.

Advertisement

Answer

That is happening due to the way Python handles variable references.

When you did

JavaScript

You’re basically sharing the variable sizes reference not it’s value. That means that forward_errors, backward_errors, magnification_factors and cond_numbers are exactly the same variable to Python.


You have some options to fix that.

1- Using the Copy library

JavaScript

2- Simply repeating the values

JavaScript

You can find more about the topic here.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement