Home > Back-end >  How do I append a value to an array in Python?
How do I append a value to an array in Python?

Time:06-04

For a numerical analysis class I need to make a for loop that must do a couple of things:

  1. Make a certain 'Dt' (a time step that gets smaller and smaller) and add this to an array called Dt_list. This must be an array containing all the different Dt's at the end of the loop

  2. Call a function called "EstimateError" with multiple parameters including Dt which changes every time the loop restarts. This function returns a one dimensional array with two components: ([est_global_error_1, est_global_error_2]) This output has to also be added to an array called: err_list being a two dimensional array.

  3. inside the for loop there must be a (nested) 'if' that checks whether or not one of the values in the global_trunction_error is smaller than or equal to 0.001, if this is the case the for loop must break.

Although seemingly easy, I can not get it to work properly after trying many variations. There seems to be something going wrong when I try to append a value to either one of the lists.

After the for-loop I must attain an optimal Dt which should be the last value on the Dt_list.

err_list = np.array([],[])
Dt_list = np.array([])


for i in np.linspace(0,100,101):
    Dt = (0.25)*(0.5)**(i)
    
    global_trunction_error = EstimateError(t_0,t_end,Dt,y_0, a,c,A,C,W_0)
    np.append(err_list, global_trunction_error)
    
    Dt_list = np.append(Dt_list, Dt)
    
    if (abs(global_trunction_error[0])) <= 0.001:
        if (abs(global_trunction_error[1])) <= 0.001:
            break

            
Dt_opt = Dt_list[-1]

CodePudding user response:

Your code starts off wrong:

In [199]: err_list = np.array([],[])    
In [200]: err_list
Out[200]: array([], dtype=[])

I expected this to raise an error, since the 2nd argument to np.array is supposed to be a dtype. Initially I was puzzled by that dtype=[], but then realized is a compound dtype with 0 fields. Normally a compound dtype looks like [('f0',float),('f1',int)], so I've never seen a 0 field dtype before.

Secondly you probably got an error like this:

In [204]: np.append(err_list, (1,2))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [204], in <cell line: 1>()
----> 1 np.append(err_list, (1,2))

File <__array_function__ internals>:5, in append(*args, **kwargs)

File ~\anaconda3\lib\site-packages\numpy\lib\function_base.py:4817, in append(arr, values, axis)
   4815     values = ravel(values)
   4816     axis = arr.ndim-1
-> 4817 return concatenate((arr, values), axis=axis)

File <__array_function__ internals>:5, in concatenate(*args, **kwargs)

TypeError: The DTypes <class 'numpy.dtype[int32]'> and <class 'numpy.dtype[void]'> do not have a common DType. For example they cannot be stored in a single array unless the dtype is `object`.

I probably should have just voted to close this question since you didn't provide any errors or their tracebacks.

First, np.append is not a list append clone! It returns a value; it does not change an array in-place.

Second, concatenating with a structured array requires arguments with a matching dtype.

On second thought, I am going to vote to close. Go back to your code and rewrite using lists and list appends. Appending values to arrays is error prone and inefficient.

CodePudding user response:

Thank you everyone for responding!

I found a way around my problem, I just divided the two dimensional array into two seperate lists and then combined them later on.

err_list_1 = []
err_list_2 = []
Dt_list = []


for i in np.linspace(1,100,10):
    Dt = (0.25)*(0.5)**(i)
    
    global_trunction_error = EstimateError(t_0,t_end,Dt,y_0, a,c,A,C,W_0)
    err_list_1.append(global_trunction_error[0])
    err_list_2.append(global_trunction_error[1])
    
    Dt_list.append(Dt)
    
    if (abs(global_trunction_error[0])) <= 0.001:
        if (abs(global_trunction_error[1])) <= 0.001:
            break

            
Dt_opt = Dt_list[-1]
err_list = np.array((err_list_1, err_list_2))

Dt_list = np.array((Dt_list))
  • Related