0

For hours I've been trying to input an equation as an argument to my function. I want the user to be able to write his own equation which my program then integrates.

The best I have got so far is this (it integrates but does not allow the user to choose the equation):

def integrate(x):
    def f(x):
        return x**2 + x * 42
    n = 10000
    a = 0 #lower limit
    b = 1 #upper limit
    small_element = (b - a) / n
    result = 0
    for k in range(0, n):
        result += f(a + (k +0.5)* small_element)
    result *= small_element
    return result

As I said, the problem with the code above is that the user does not choose the equation. This program only works on this particular equation of x**2 + x * 42 which I wrote down myself. How do I allow the user to input a mathematical equation himself? For example, I would like him to be able to write in the console:

Integrate(x**3 + x**2 + x + 42)

which would then input the equation into my program and integrate it accordingly.

I was also thinking about putting the equation as a string and somehow making it into an float-kinda thing but that didn't work either.

demongolem
  • 9,474
  • 36
  • 90
  • 105
Bitrsweet
  • 1
  • 1
  • 5
    `Integrate(lambda x: x**3 + x**2 + x + 42)`? – jonrsharpe Nov 15 '16 at 20:23
  • You could define a `Var` type that implements `__add__`, `__mul__` etc and whose `__call__` returns the result of the expression you described... This would allow things like: `x = Var(); Integrate(x**3 + x**2 + x + 42)`. For multi-variate functions you'll need variable names. – Bakuriu Nov 15 '16 at 20:24
  • [Help--Function Pointers in Python](http://stackoverflow.com/a/402369/7163961) – Mike Nov 15 '16 at 20:26
  • Jonrsharpe: I tried using what you mentioned as an input after deleting 2nd ar 3rd lines but it didn't quite work as then my 3rd line from the bottom doesn't make sense. Would be great if you could explain a bit what you meant. Bakuriu: sorry but I'm not familiar with __add__, __call__ and such at all. When you say define a variable do you mean before the function say x = __add__ ? Or is it inside the function? Mike: Sorry again but after looking to the post you mentioned I still have no idea how to implement that to my program :( – Bitrsweet Nov 15 '16 at 20:45
  • 1
    Have a look here. This answers your question: [Equation parsing in Python](http://stackoverflow.com/questions/594266/equation-parsing-in-python) – Ukimiku Nov 15 '16 at 20:45
  • The proper way to do this is with an expression parser. You _could_ do this using `eval`, but as mentioned in the linked answers `eval` (and `exec`) should generally be avoided because they can be a security risk. For details, please see [Eval really is dangerous](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) by SO veteran Ned Batchelder. – PM 2Ring Nov 15 '16 at 21:02

0 Answers0