ellen
ellen

Reputation: 704

Preventing overflow in python

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!

Upvotes: 0

Views: 197

Answers (1)

Reblochon Masque
Reblochon Masque

Reputation: 36682

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])

Upvotes: 1

Related Questions