arithmetic_derivative.sf 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 21 February 2017
  5. # https://github.com/trizen
  6. # Recursive implementation of the arithmetic derivative rule.
  7. # (with support for rational and negative values)
  8. # See also:
  9. # https://oeis.org/A003415
  10. # https://en.wikipedia.org/wiki/Arithmetic_derivative
  11. subset Integer < Number { .is_int }
  12. subset Positive < Integer { .is_pos }
  13. subset Negative < Integer { .is_neg }
  14. subset Prime < Positive { .is_prime }
  15. func arithmetic_derivative((0)) { 0 }
  16. func arithmetic_derivative((1)) { 0 }
  17. func arithmetic_derivative(_ < Prime) { 1 }
  18. func arithmetic_derivative(n < Negative) {
  19. -arithmetic_derivative(-n)
  20. }
  21. func arithmetic_derivative(n < Positive) is cached {
  22. var a = n.factor.rand
  23. var b = n/a
  24. arithmetic_derivative(a)*b + a*arithmetic_derivative(b)
  25. }
  26. func arithmetic_derivative(Number n) {
  27. var (a, b) = n.nude
  28. (arithmetic_derivative(a)*b - arithmetic_derivative(b)*a) / b**2
  29. }
  30. for n in (-10..20) {
  31. printf("%2s' = %s\n", n, arithmetic_derivative(n))
  32. }
  33. say "\n=> Other values:"
  34. printf("( 3/4)' = %s\n", arithmetic_derivative(3/4).as_frac)
  35. printf("(24/7)' = %s\n", arithmetic_derivative(24/7).as_frac)
  36. printf("( 7!)' = %s\n", arithmetic_derivative(7!))
  37. printf("( 11#)' = %s\n", arithmetic_derivative(11.primorial))