Numerical tools

Work with integer bits, primes, factors, polynomials and numerical searches

Continue from Rearranging and transforming arrays.

Bit operations

ᵇ (Bitwise)

In binary, the digit positions have values 1, 2, 4, and so on, counting from the right. The digits are 0 or 1, called bits. Six is binary 110 and three is 011. Bitwise applies a Boolean function separately to each bit. ∧ keeps a 1 only where both have a 1, giving binary 010, or two:

6∧ᵇ3
2ₓ
6∨ᵇ3
7ₓ
6≠ᵇ3
5ₓ

Mathematical tools

⍭ (Primes)

A prime is an integer greater than 1 divisible only by itself and 1. ⍭n gives the prime with n primes before it. Position 0 is the prime 2:

⍭⍳8ₓ
[2 3 5 7 11 13 17 19]ₓ

On a prime, the inverse gives its position. It counts the primes strictly below its argument, including when the argument is not itself prime:

⍭⁻¹11
⍭⁻¹10
4ₓ
4ₓ

A left argument chooses another prime operation. Code 1 tests whether a number is prime; code 2 gives the next prime:

1⍭1 2 3 4 5 6
$f $t $t $f $t $f
2⍭10 11 12
[11 13 13]ₓ

⨸ (Factors)

A number’s prime factors are primes whose product is that number. Factors gives them in ascending order, with repetitions. Multiplying them recovers the number:

⨸360ₓ
[2 2 2 3 3 5]ₓ
×/⨸360ₓ
360ₓ

Factors’ inverse multiplies the factor list back into the number.

⨸⁻¹[2 2 2 3 3 5]ₓ
360ₓ

An exponent counts the copies of one prime factor in the product. A left argument of ¯∞ gives a table of distinct factors above their exponents:

¯∞⨸360ₓ
[2 3 5
 3 2 1]ₓ

⌻ (Polynomials)

A polynomial is a sum of multiples of nonnegative integer powers, such as 1 + 2x + 3x². The multipliers 1 2 3 are its coefficients, starting with the constant term: the part without x. Fixing that left argument makes a polynomial function:

p←[1 2 3]⌻
p[0 1 2]
1 6 17

Derivative applies to this function too:

p∂2
14

A root is an input where the polynomial is zero. With one argument, ⌻ gives the coefficient of the highest power and the approximate roots. For x² − 3x + 2, that coefficient is 1 and the roots are 1 and 2:

⌻2 ¯3 1
[1 [1 2]]

The inverse rebuilds the coefficients from the highest-power coefficient and roots.

⌻⁻¹[1 [1 2]]
2 ¯3 1

⇄ (Optimize)

Optimize searches for the point where a function is least, starting from its argument. The squared distance from 2 is least at 2:

cost←{(⍵-2)²}
cost⇄10
2

With "solve":$t, it instead searches for a zero. This finds the positive square root of 2, starting from 1:

["solve":$t] {⍵²-2}⇄ 1
1.414213562

Previous: Rearranging and transforming arrays · Study guide