test_interface.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # This test file tests the SymPy function interface, that people use to create
  2. # their own new functions. It should be as easy as possible.
  3. from sympy.core.function import Function
  4. from sympy.core.sympify import sympify
  5. from sympy.functions.elementary.hyperbolic import tanh
  6. from sympy.functions.elementary.trigonometric import (cos, sin)
  7. from sympy.series.limits import limit
  8. from sympy.abc import x
  9. def test_function_series1():
  10. """Create our new "sin" function."""
  11. class my_function(Function):
  12. def fdiff(self, argindex=1):
  13. return cos(self.args[0])
  14. @classmethod
  15. def eval(cls, arg):
  16. arg = sympify(arg)
  17. if arg == 0:
  18. return sympify(0)
  19. #Test that the taylor series is correct
  20. assert my_function(x).series(x, 0, 10) == sin(x).series(x, 0, 10)
  21. assert limit(my_function(x)/x, x, 0) == 1
  22. def test_function_series2():
  23. """Create our new "cos" function."""
  24. class my_function2(Function):
  25. def fdiff(self, argindex=1):
  26. return -sin(self.args[0])
  27. @classmethod
  28. def eval(cls, arg):
  29. arg = sympify(arg)
  30. if arg == 0:
  31. return sympify(1)
  32. #Test that the taylor series is correct
  33. assert my_function2(x).series(x, 0, 10) == cos(x).series(x, 0, 10)
  34. def test_function_series3():
  35. """
  36. Test our easy "tanh" function.
  37. This test tests two things:
  38. * that the Function interface works as expected and it's easy to use
  39. * that the general algorithm for the series expansion works even when the
  40. derivative is defined recursively in terms of the original function,
  41. since tanh(x).diff(x) == 1-tanh(x)**2
  42. """
  43. class mytanh(Function):
  44. def fdiff(self, argindex=1):
  45. return 1 - mytanh(self.args[0])**2
  46. @classmethod
  47. def eval(cls, arg):
  48. arg = sympify(arg)
  49. if arg == 0:
  50. return sympify(0)
  51. e = tanh(x)
  52. f = mytanh(x)
  53. assert e.series(x, 0, 6) == f.series(x, 0, 6)