Pyli/Methods/Number

From Jonathan Gardner's Tech Wiki
< Pyli‎ | Methods
Jump to: navigation, search

Numbers

Typecasting

Every object may present the following methods:

  • integer: Convert to an integer.
  • float: Convert to a float.
  • decimal: Convert to a decimal.

Which one is preferred? That's a hard game to play.

Simple Tests

  • (zero? n): True if n == 0
  • (non-zero? n): True if n != 0
  • (plus? n): True if n > 0
  • (minus? n): True if n < 0

The above are merely shortcuts that will dispatch to the following. It should make your code a bit more readable.

Comparators

  • (< a b ...):
  • (< a b): True if a < b
  • (< a b c d): True if a < b < c < d
  • (> ...), (<= ...), (>= ...), (= ...), (!= ...)

How do these work? The compare method of an object is called. If it doesn't recognize the other type, it signals a ValueError. Then the order is reversed and it is compared again. If that fails, then the typecasting is attempted.

Basic Math

  • (sign n): +1, 0, -1 depending on sign.
  • (abs a): Returns a with sign removed.
  • (gcd ...): Greatest common divisor for all the args, 1 if False.
  • (lcm ...): Least common multiple of all the args, 1 is False.

Basic Arithmetic

How do you add different types?

Each object may specify '+', '-', '*', '/' methods.

  • '+' is binary. It takes self and other. Signal a ValueError if the other type isn't supported.
  • '-' is unary. It inverts the sign of the object.
  • '*' is binary. Like '+'
  • '/' is unary. It should return 1/self. (Integers shouldn't upgrade to a float. Probably shouldn't implement this.)

Otherwise, typecasting is used.

  • (+ ...)
    • (+) => 0
    • (+ a) => a
    • (+ a b c d) => a + b + c + d
  • (- a b ...): Subtraction
    • (- a) => (- 0 a) => -a
    • (- a b) => a - b
    • (- a b c d) => a - b - c - d
  • (* ...):
    • (*) => 1
    • (* a) => a
    • (* a b c d...) => a * b * c * d
  • (/ a b ...): Division, not floor. This will give you a float, perhaps.
    • (/ a) => 1 / a
    • (/ a b) => a * 1/b => a / b
    • (/ a b c d) => a / b / c / d

Trigonometry

  • e
  • pi
  • (cos a), (sin a), (tan a), acos, cosh, pow, log, ln, ... all the trig functions

Statistics

  • (mean ...)
  • ...

Calculus

Is it possible to define a simple set of derivatives and integrals, or should we leave that for a real module that handles real numbers?