开发者

How to take a function as an argument? (Python)

I'm writing a program to calculate the volume of a solid of rotation. The first step of this is to calculate an integral. I'm using scipy.integrate for this, but I can't figure out the best way to have a equation (like x=x**2 input at the command line. I was originally planning on adding an argument 'with respect to: x|y' and then taking the function as a lambda. Unfortunately, argparse won't take lambda as an argument type, and trying to use a string to construct a lambda (f = lambda x: args.equation) just returns a string (understandably really).

Here's what I've got so far:

import sys
import argparse
import math
from scipy import integrate

parser = argparse.ArgumentParser(description='Find the volume of the solid of rotation defined')
parser.add_argument('equation', help='continous function')
parser.add_argument('a开发者_StackOverflow', type=float, help='bound \'a\'')
parser.add_argument('b', type=float, help='bound \'b\'')
parser.add_argument('-axis', metavar='x|y', help='axis of revolution')
args = parser.parse_args()

def volume(func, a, b, axis=None):
  integral = integrate.quad(func, a, b)
  return scipy.py * integral

print volume(args.equation, args.a, args.b)

Any advice will be appreciated thanks


If there are absolutely no concerns about security risks from letting the user run arbitrary Python code, then you can use eval to create a callable object:

volume(eval('lambda x: %s' % args.equation), args.a, args.b)


You should be able to use eval() on the string you get from your arguments:

>>> f = eval("lambda x: x**2")
>>> f(5)
25
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜