0

Python newbie here using Python 2.7 and working from a boilerplate. I came across this line in a boilerplate function which is causing problems for me:

x[x < -100] = -100

The comment says that this is supposed to prevent overflow, but I have no idea how. The x that I am passing in is a float. I tried searching the python documentation but maybe I was using the wrong keywords? Can anybody help me understand this? Thanks!

3
  • 3
    Is this using Numpy? It supports some shenanigans like this. Commented Nov 24, 2017 at 3:57
  • 1
    if x is a float then this code will raise a TypeError because floats don't support indexing. Commented Nov 24, 2017 at 4:00
  • There is some numpy going on - maybe that's the documentation I should be searching. And yes, it absolutely throws a TypeError! Commented Nov 24, 2017 at 4:06

1 Answer 1

1

This is what this line is doing:

every value in x whose value is lower than -100 is set to -100

import numpy as np
import random

x = np.array([random.randrange(-1000, 1000) for _ in range(100)])

x[x < -100] = -100    # every value in x whose value is lower than -100
                      # is set to -100
x

output:

array([-100, -100,  653,  466,  268,  194,  835, -100, -100, -100, -100,
        760,   15,  303,  331,  575,  289,  -87, -100, -100, -100,  686,
       -100, -100, -100, -100,  961, -100,  745,  -94, -100, -100,  967,
       -100,   22, -100,  198, -100, -100, -100,   41, -100,  156, -100,
       -100,  620, -100,   32,  -97, -100, -100,  390, -100,  -28,  539,
        412, -100, -100,  -36, -100,  682,  203,   57,  368,  876,  646,
       -100,  307, -100, -100,   29, -100,  999, -100, -100, -100, -100,
       -100,  234,  758,  132,  116, -100,  485, -100,  201, -100, -100,
        997, -100,  575,   -3,  610,  739, -100, -100, -100,  717,  939,
       -100])
Sign up to request clarification or add additional context in comments.

2 Comments

That makes sense! Thanks
this answer deserves +1 unlike yesterday! :)

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.