社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在python函数中添加f(x)作为参数?

bacjist • 4 年前 • 871 次点击  

好的,所以我试图在某个范围内找到函数f(x)的最大值,在x发生这种情况。python函数的参数应该是(f(x),[a,b])。f(x)是任意函数,[a,b]是我们要研究的范围。

def maxf(function,interval):
  maxresult = 0
  for x in range(interval[0]-1,interval[1]+1):
    result=float(function.replace("x",str(x)))
    if result >= maxresult:
      maxresult = result
      maxresultx = x

  return maxresult,maxresultx
print(maxf("x**2",[1,3]))

这一个返回:

Traceback (most recent call last):
  File "main.py", line 10, in <module>
    print(maxf("x**2",[1,3]))
  File "main.py", line 4, in maxf
    result=float(function.replace("x",str(x)))
ValueError: could not convert string to float: '0**2'

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54240
 
871 次点击  
文章 [ 3 ]  |  最新文章 4 年前
blue_note
Reply   •   1 楼
blue_note    4 年前

你的问题是 float() 接受一个字符串 已经表示一个浮点数 float("1.23") ,而不是将导致一个(例如 float("2**3") ). 所以,必须首先计算字符串。

float(eval("3**2"))

eval()

Jean-Baptiste Yunès
Reply   •   2 楼
Jean-Baptiste Yunès    4 年前

使用这个:

def maxf(function,interval):
  maxresult = 0
  for x in range(interval[0]-1,interval[1]+1):
    result=float(function(x))
    if result >= maxresult:
      maxresult = result
      maxresultx = x

  return maxresult,maxresultx
print(maxf(lambda x: x**2,[1,3]))

lambda 定义作为参数传递的函数(匿名函数),因此 maxf 可以根据需要调用它。

Eternal
Reply   •   3 楼
Eternal    4 年前

问题是字符串实际上没有被计算。它只是被转换成float,所以错误提示您正在做的是将“0**2”转换成float,这是不可能的,您可以做的是使用eval函数来计算任何给定的字符串,然后比较结果。

你只需要做这样一个小小的改变:

result=eval(function.replace("x",str(x)))

这还不是最好的方法,您应该在那里使用生成器:

def maxf(function,interval):
  maxresult = 0
  for x in range(interval[0]-1,interval[1]+1):
    yield eval(function.replace("x",str(x))), x


print(max(maxf("x**2", [1, 3])))

a_list = [1,3]

max_item = max(a_list, key=lambda x: eval("x**2"))

print(eval("x**2".replace("x", str(max_item))), max_item)