防止python溢出

时间:2017-11-24 03:55:40

标签: python

Python新手在这里使用Python 2.7并在样板文件中工作。我在样板函数中遇到了这一行,这给我带来了问题:

x[x < -100] = -100

评论说这可以防止溢出,但我不知道如何。我传入的x是一个浮点数。我试过搜索python文档,但也许我使用了错误的关键字?任何人都可以帮我理解这个吗?谢谢!

1 个答案:

答案 0 :(得分:1)

这就是这一行:

x中值低于-100的每个值都设置为-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

输出:

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