'Algebra math expression translated to python function with 2 inputs and a rounded answer

Learning math to python conversion. Having trouble translating this math expression to a python function with two inputs (x, y). Help would be appreciated. I will have to catch up on my order of calculations its seems. Also some resources where I can learn more about this myself would be great. Thanks :)

math expression

The input variables x and y are single values If a division by zero occurs, raise a ValueError. Output should be rounded to 2 decimal places. You can calculate 𝑒𝑥 using the NumPy function np.exp(x)

def math_func(x, y):
    math_func = math.pi*np.exp(x))**2 / 4(y)
    return round(math_func, 2)


Solution 1:[1]

The following implements that mathematical function. You forgot to square the x. I recommend using parentheses to separate the numerator and denominator. It saves you from having to remember all the operator precedence and associativity rules. Moreover, you need to explicitly write 4 * y to multiply the two numbers ( 4y is a SyntaxError).

from math import exp, pi
def foo(x, y):
    try:
        res = (pi * exp(x * x)) / (4 * y)
    except ZeroDivisionError:
        raise ValueError
    return round(res, 2)

print(foo(2, 5))

Output

8.58

To sample dividing by zero, try foo(2, 0). The traceback message should indicate that a ZeroDivisionError occurred and that during handling of that exception, ValueError occurred.

Solution 2:[2]

You have several issues.

  • avoid using the function name as internal variable (here I used z)
  • you can't make implicit multiplications (use 4*y, 4(y) would mean you try to use 4 as a function, which is impossible)
  • you had a wrong precedence: e^x^2 is e^(x^2)
  • (minor) if you already import numpy you can use numpy.pi

corrected version

def math_func(x, y):
    import numpy as np
    z = np.pi*np.exp(x**2) / (4*y)
    return round(z, 2)

math_func(3, 4)
# 1591.04

Regarding the ValueError, unless this is for an assignment (in which case you can use try/except), it is probably better to keep the ZeroDivisionError that is more explicit than the more generic ValueError

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2