如何让用户决定一个范围界定的系列的增量?

时间:2017-11-13 02:56:41

标签: python python-3.x numpy

我想打印一个数字列表,该数字列表以增量值的范围-2< = x< = 2为界,这样列表总是以-2开头并以2结束,反之亦然。我想让用户输入一个增量值,即0.5或0.05。从上面给出的范围可以看出,最大的增量是4.

每当用户输入的增量值为>时,我都希望提示错误消息。 4当他们输入一个增量值时,该值不允许列表从2开始打印并在-2处结束,即当增量值为0.23时。

我认为我可以做的方法是使用模数运算符,其中if(4%增量值)= str(),即整数意味着给定的增量值对该范围有效。但是我有点卡住,因为当我运行我的代码时,我最终陷入了一个永无止境的循环。以下是我到目前为止所做的事情,所以希望有人可以帮助我:

def IncCheck():
    while True:
        try:     #I first check if the user inputs me a string then an error message would come up
            c = float(input("For the range -2 <= x <= 2, please input the increment you wish to display: "))
            break
        except ValueError:
            print("Invalid input. The increment has to be a number.")
    while 4%c != int():    #Here I wanna check the validity of the increment value so ideally it'd be < 4 and be a value that prints a list that starts with -2 and ends with 2.
        print("Your selected increment is not valid for -2 <= x <= 2. It should be a divisible increment of 4(the range). Please try again.")
        if c > 4:
            print("Your increment is too high. The maximum increment for the given range is 4. Please try again.")
    return c

print(IncCheck())

正如你所看到的,我试图创建一个检查增量的函数。最后我想用

之类的东西打印列表
import numpy as np
for i in np.arange(2, -2-c, -c): #c is the increment value the users input
    print i 

我可以用来做其他事情。我需要使用这些x值并将它们绘制成arctan(x)函数,我使用具有N值的泰勒级数近似,即泰勒级数中的迭代次数,并将它们与真实的arctan并排比较( x)基本功能。然后绘制图形。提前谢谢。

2 个答案:

答案 0 :(得分:0)

让增量为c

  • 如果c小于0,请检查
    • 通过评估X
    • 找到2 + (cX) = -2
    • 通过将X插入上述公式并验证结果
    • 来检查c
  • 如果X大于0,则检查
    • 通过评估-2 + (cX) = 2
    • 找到X
    • 通过将max-height:插入上述公式并验证结果
    • 来检查.list-group{ max-height: 300px; margin-bottom: 10px; overflow:scroll; -webkit-overflow-scrolling: touch; }
  • 否则,不可能 - 不能以零增量去任何地方。抛出异常或打印错误消息

答案 1 :(得分:0)

我就是这样做的(没有用户输入例程)

def increment_(c, start = -2, end = 2):
    assert np.isclose((end - start) % c, 0), "Step does not evenly divide range"
    steps = (end - start) / c
    if np.signbit(steps):
        return np.linspace(end,   start, - int(steps) + 1)
    else:
        return np.linspace(start, end,     int(steps) + 1)

用户输入中的无限循环在this question中解释,其中@wwii链接在评论中