scipy_nodes.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. from sympy.core.function import Add, ArgumentIndexError, Function
  2. from sympy.core.singleton import S
  3. from sympy.functions.elementary.trigonometric import cos, sin
  4. def _cosm1(x, *, evaluate=True):
  5. return Add(cos(x, evaluate=evaluate), -S.One, evaluate=evaluate)
  6. class cosm1(Function):
  7. """ Minus one plus cosine of x, i.e. cos(x) - 1. For use when x is close to zero.
  8. Helper class for use with e.g. scipy.special.cosm1
  9. See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.cosm1.html
  10. """
  11. nargs = 1
  12. def fdiff(self, argindex=1):
  13. """
  14. Returns the first derivative of this function.
  15. """
  16. if argindex == 1:
  17. return -sin(*self.args)
  18. else:
  19. raise ArgumentIndexError(self, argindex)
  20. def _eval_rewrite_as_cos(self, x, **kwargs):
  21. return _cosm1(x)
  22. def _eval_evalf(self, *args, **kwargs):
  23. return self.rewrite(cos).evalf(*args, **kwargs)
  24. def _eval_simplify(self, x, **kwargs):
  25. candidate = _cosm1(x.simplify(**kwargs))
  26. if candidate != _cosm1(x, evaluate=False):
  27. return candidate
  28. else:
  29. return cosm1(x)