返回等式最接近零的输入数

时间:2015-04-21 04:29:28

标签: python range output equation

我正在尝试将一系列值输入到等式中,然后返回等式最接近零的输入值。目前我有:

def function():
    bestNumber = 10000000000 #an obscenely large number to start from
    for input in range(15):
        pos = 2 * (10**10.5)/(10**10.5+10**input)
        neg = 2 * (10**3.86)/(10**3.86+10**input)
        finalNumber = pos - neg
        if finalNumber < bestNumber:
            bestNumber = finalNumber
    print (bestNumber)
    print (input)
function()

>>>0.0002760
>>>14

当然,此函数将始终打印一个非常接近0的数字,但只是打印循环中的最后一个值。

我真的很难找到一种方法来返回导致input最低值的bestNumber值。我觉得我很接近但是缺少一些关于循环的关键知识。

3 个答案:

答案 0 :(得分:2)

首先:只需输入您的函数来计算您的值 -

def function(input):
    pos = 2 * (10**10.5)/(10**10.5+10**input)
    neg = 2 * (10**3.86)/(10**3.86+10**input)
    return pos - neg

第二:您可以使用list comprehension(此处为技术上的生成器表达式)生成您的值,并将其传递给内置min函数 -

bestNumber, input = min((function(i), i) for i in range(15))
# (0.00027603868572034784, 0)

答案 1 :(得分:1)

您可以添加另一个跟踪相关最佳输入的变量:

def function():
    bestNumber = 10000000000 #an obscenely large number to start from
    bestInput = 0
    for input in range(0,15):
        pos = 2 * (10**10.5)/(10**10.5+10**input)
        neg = 2 * (10**3.86)/(10**3.86+10**input)
        finalNumber = pos - neg
        if finalNumber < bestNumber:
            bestNumber = finalNumber
            bestInput = input
    return (bestInput, bestNumber)

bestIn, bestNum = function()
print(bestIn)
print(bestNum)

>>>0
>>>0.00027603868572034784

编辑: 这不检查十进制数,范围返回整数列表。你可以这样做:

def function():
    bestNumber = 10000000000 #an obscenely large number to start from
    bestInput = 0
    input = 0
    while (input < 15):
        pos = 2 * (10**10.5)/(10**10.5+10**input)
        neg = 2 * (10**3.86)/(10**3.86+10**input)
        finalNumber = pos - neg
        if finalNumber < bestNumber:
            bestNumber = finalNumber
            bestInput = input
        input = input + 0.1
    return (bestInput, bestNumber)

bestIn, bestNum = function()
print(bestIn)
print(bestNum)

>>>14.999999999999963
>>>6.324353877789737e-05

检查功能图,最小值接近0或15。

答案 2 :(得分:0)

您可以在循环的第一次迭代期间存储第一个bestNumber值,而不是以巨大的finalNumber值开头。

然后使用bestNumber来比较以下迭代:

def function():
    for input in range(15):
        pos = 2 * (10**10.5)/(10**10.5+10**input)
        neg = 2 * (10**3.86)/(10**3.86+10**input)
        finalNumber = pos - neg
        if input==0:  
            bestNumber=finalNumber         #store bestNumber for the first iteration
        elif finalNumber < bestNumber:     #compare bestNumber for following iterations
            bestNumber = finalNumber
    print (bestNumber)
    print (input)
function()

>>> 
0.00027603868572
14