**Python Number: random, float and divmod**Use numbers and numeric operators. See the add, multiply, subtract and divide constructs.

dot net perls

**Numbers.** It is 2 PM. It is 50 degrees F. There is a beauty in numbers. Human beings use them to describe our world. Programs too are built of numbers.

**Operators.** Tiny functions called operators act upon numbers. With operators and operands (the values operated upon), we make expressions and statements.

**Division.** We have two division operators. With one slash, we divide two numbers. And with two slashes "//" we divide and round down the result.

**Operator 1** The "/" operator leaves the fractional part of the result intact. It does not matter if the two operands are fractional or not.

**Operator 2** The "//" operator divides in the same way. But it also rounds the result down to the nearest integer.

Python program that divides numbers

a = 100
b = 7

*
# Divide 100 by 7.
*print(a / b)

*
# Discard fractional part of result.
*print(a // b)

14.285714285714286
14

**Integral division.** This operator does not round up if the value is closer to the higher value. This means 5 // 3 will give 1, even though 5 / 3 gives 1.6, which is closer to 2 than to 1.

Python common line division

>>> 5//3
1
>>> 5/3
1.6666666666666667

**Float** converts data to floating-point numbers. It acts on string values (like "10.0") or integers (like 10). On strings, it handles signs (positive or negative) and infinity values ("inf").

**Conversion** Float is similar to other built-ins like int or str. Python simplifies common conversions.

Convert

Python program that uses float

*# Float converts a string into a float number.
*value =

*"3.14"*
number =

__float__(value)
print(number)
print(number == 3.14)
print(value == "3.14")
print()

*
# Float also converts an integer into a float number.
*integer =

*100*
floating =

__float__(integer)
print(floating)
print(integer)

3.14
True
True
100.0
100

**Int.** Like float, int() converts from strings and other number types. It returns an integer (a number with nothing past the decimal—no fractional part).

Int

**Note** Int will cause an error if we try to convert a floating-point number within a string (like "123.4").

Python program that uses int

*# Convert a string to int.
*input =

"123"
result =

__int__(input)
print(result)

*
# Use int to convert from floating to integral.
*input =

456.9
result =

__int__(input)
print(result)

123
456

**Hex** converts an integer into a hexadecimal number. This form of number can be useful in interoperating with other programs and systems. We see the hex representations of 10 and 100.

Python program that uses hex

*# Convert this value to a hex.
*value = 10
result =

__hex__(value)
print(result)

*
# Convert another value.
*value = 100
result =

__hex__(value)
print(result)

0xa
0x64

**Octal numbers** use not a base 10 like we are used to, but a base 8. So they only contain the digits 0 through 7. With oct() we convert a base 10 number into its octal representation.

Python program that uses oct

*# Convert 74 into octal which is 112.
*number =

*74*
octal =

__oct__(number)
print(octal)

0o112

**Bits.** In computers, numbers are presented with bits, as binary. With the bin() built-in, we get a string representation of an integer. Zeros on the left of the representation are discarded.

**Negative** The sign bit is represented by the 0 before the lowercase "b." A -1 has a leading minus sign.

Python program that uses bin

number =

100*
# Convert this number to a binary string.
*result =

__bin__(number)
print(result)

0b1100100

bin(-1) -0b1
bin(0) 0b0

**Complex.** Complexity is not just in our computer programs. We also encounter complex numbers. These numbers have two components—real and imaginary.

**Imaginary unit** Complex numbers include an "imaginary unit" that is separate from the real parts. These numbers never become bored.

**Info** In Python we have the complex() built-in function. These numbers can be added, subtracted, and manipulated in other ways.

Python program that uses complex numbers

*# Create two complex numbers.
*complexA =

__complex__(3, 10)
complexB =

__complex__(5, 15)

*
# Add the two together.
# ... The result is also complex.
*complexC = complexA + complexB
print(complexC)

(8+25j)

**Benchmark, division.** Division is a slow operation on processors. In Python we have both the "/" and "//" operators. Is there some optimization in the latter one? My benchmark tests this.

**Version 1** This version of the code uses the single-slash operator to perform a division.

**Version 2** Here we use the double-slash operator to perform division and get an integer-only result.

**Result** We find that the "//" operator is slower than the "/" operator. It adds steps beyond the regular operator.

Python program that times division

import time
a = 1000
b = 223
c = 0
print (time.time())

*
# Version 1: normal division
*i = 0
while i < 10000000:
c = a / b
i += 1
print (time.time())

*
# Version 2: integer result division
*i = 0
while i < 10000000:
c = a // b
i += 1
print (time.time())

1345843075.764
1345843077.922 (/ =

2.158 s)
1345843080.448 (// =

2.526 s)

**Divmod, modulo.** The divmod function is built into the Python language. It computes two kinds of division at once: it does an integral division and a modulo division. It returns a tuple.

Divmod

**Random numbers** can be generated in Python with the randint method. But for a random selection in a list or other collection, random.choice is an ideal option.

Random

**Pow.** The pow built-in, or two asterisks, means exponentiation. We can raise a number to a certain power with clear syntax. The two syntax forms are equivalent.

pow

**Bool** converts an expression into True or False. It is similar to the if-statement, which also evaluates expressions. Bool is a value—often languages store False as 0 and True as 1.

bool

**Is a number prime?** We implement a prime-testing method with a def and a for-loop. Some arithmetic optimizations are applied to this method—we test the number's square.

Prime Number

**Numeric operations** are everywhere. All memory accesses in programs use numeric computations. An access to an element of a list, at an index, requires multiplications to locate memory.

**Compilers handle these.** A simple program is an illusion. All programs involve complex numeric computation. All levels of programming, from the metal to object models, are numeric.

© 2007-2021 sam allen. send bug reports to info@dotnetperls.com.