1

I want to redefine array elements in my function roll

roll_current = 0

def roll(t):
    global roll_current

    # Generate array of the same numbers
    roll_current_ =  np.full((len(t)), roll_current)

    delta_roll_ = 0.1 - np.exp(-t)
    diff_ = roll_current_ - delta_roll_     

    # Update roll_current_ array
    for i, x in enumerate(roll_current_):
        if diff_[i]>0:
            roll_current_[i] = x - abs(diff_[i]) # x is equal to roll_current_[i] 
        elif diff_[i]<0:
            roll_current_[i] = x + abs(diff_[i]) 

    # Save value for the last time step
    roll_current = roll_current_[-1] # Scalar

    return roll_current_

But if I use -= or +=assignment or the code above then roll_current_ array doesn't change and the following lines

t = np.linspace(0,4,10)
roll(t)

give array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

What is wrong?

0

2 Answers 2

1

I found the problem in your code:

The fill method fills an array with the value of roll_current which is an integer. Thus the array will also be of type int. Then in the for-loop all the values you are trying to set are between -1 and 1 and are therefor rounded to zero. To solve the problem, change this line

roll_current_ =  np.full((len(t)), roll_current)

to this

roll_current_ =  np.full((len(t)), roll_current, dtype = np.float)

Alternatively you could just initialize roll_current like this:

roll_current = 0.
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks it saved me) But what do you mean when say "Alternatively you could just initialize roll_current like this" ? Because it seems I use exactly this type of initialization
Do you mean roll_current_ = 0?
The difference is the point behind the zero. When you write roll_current = 0 python will use the type int, when you write roll_current = 0. or roll_current = 0.0 it will be a float and since roll_current_ is initialized with the value of roll_current it will also be an array of floats
Got it. Thank you again
0

If you do a print of roll_current_ = np.full((len(t)), roll_current) output:

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

probably you doesnt want this.

Please dont use globals if you can avoid it, why not def roll(t, roll_current)?

At for loop dont update the same array you are iterating, instead build another array appending the new items.

1 Comment

Thanks, problem had the different nature as @markuscosinus mentioned

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.