1

I am trying to write a simple function that converts an input written in LaTeX to a ufunc that can be read by numpy. So far, I'm testing the function by converting \sin(x) to np.sin(x) (ignoring the conversion from {} to (). I'm not that familiar with ufuncs so I keep running into an error when trying to convert the \sin(x) string to the np.sin(x) ufunc for any given x.

import numpy as np

latexEq = input()

def latexMap(latexEq):
    if "\sin" in latexEq:
        sinLatex = latexEq.replace("\sin", "np.sin")
    else:
        pass
    return sinLatex

npOutput = np.ufunc(latexMap(latexEq))
print(f"f(x)={numpyOutput}")

Similar to how an integer may be converted into a string str(2), I tried enclosed both sinLatex, latexEq, "np.sin", and npOutput but the error I always receive is

TypeError: cannot create 'numpy.ufunc' instances

Any explanation would be appreciated.

Unmaxed
  • 15
  • 3
  • What about just returning `np.sin`? – monk Dec 27 '22 at 00:48
  • I can't do that because I'm planning to use this type of function to convert more complex LaTeX to NumPy ufuncs. – Unmaxed Dec 27 '22 at 01:03
  • `np.sin` is a Python function. `np.ufunc` does not convert a string to the function. – hpaulj Dec 27 '22 at 01:34
  • I do not think this approach of converting LaTeX to NumPy you are going for is going to work well. There is a lot of work done already into parsing equations like [`latex2sympy2`](https://github.com/OrangeX4/latex2sympy) which should give you some ideas. – monk Dec 27 '22 at 01:40
  • You can map string to functions with a `dict`, e.g. `{'sin':np.sin, 'cos': np.cos}`. – hpaulj Dec 27 '22 at 02:25

1 Answers1

0

So if you just have npOutput = "np.sin" (without the (x)) you can do

# function_name = getattr(module, function_name_string)
npOutput = getattr(np, npOutput.lstrip("np."))

which gives you the function np.sin. The parentheses have to be gone because otherwise it would be a function call, not a function.

yagod
  • 330
  • 1
  • 8