28
WHAT KIND OF THING IS IT? Python: Basic Numeric Types http://www.flickr.com/photos/iamthestig2/3925864142/sizes/l/in/ photostream/

WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Embed Size (px)

Citation preview

Page 1: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

WHAT KIND OF THING IS IT?

Python: Basic Numeric Types

http://www.flickr.com/photos/iamthestig2/3925864142/sizes/l/in/photostream/

Page 2: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Data Types

All data in the computer is stored as a sequence of bitsThese bits can mean different things depending on

how they are interpreted.A data type is a way of interpreting the meaning of the

bits and also a specification of how to process those bits.

More specifically, a data type is defined by The set of values that are elements of the type The set of operations that can be applied on those values

Python has a set of pre-defined (built-in) types and programmers are also free to define their own data types.

2

Page 3: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Built in Types

The principal built-in types are numerics, sequences, mappings, files, classes, instances and exceptions.

There are three basic numeric types int – unlimited (arbitrary) precision float – usually 64 bits of precision (system dependent) complex – two floats the real and imag (z.real and

z.imag)Default types

A sequence of digits is an int A sequence of digits that includes a ‘.’ is a float

3

Page 4: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Types

The function “type” will accept a value and return the values type type(32) type(“32”) type(3.1)

There are function to convert to other types int(32) int(35235252352369482358235923583469146) float(352352.1) complex(3.2, 18.5)

Page 5: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Notes on Type Conversion Functions

int(x, base) : converts x to an int if x is a number, then it is converted to an int if x is a string and base is not given, then x is

converted to an int with a base of 10 if x is not a number OR if base is given, then x must be

a stringfloat(x) : converts x to a float

x may be a string or a number If x is outside the range of a Python float, an

OverflowError will be raised.

Page 6: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Notes on Min/Max others

The minimum and maximum float values are sys.float_info.max sys.float_info.min

There are several special float values x = float('+inf') y = float('-inf') z = float('nan') a = x / y

There is no minimum nor maximum for int. Why?

Page 7: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Expressions

Expressions are code fragments that compute new values by combining other values.

Expressions involve operators. An operator acts on values. An operator is characterized by arity – the number of inputs precedence – the order of application in an expression

involving more than one operator associativity – the order of application in an

expression involving more than on occurrence of the same operator.

7

Page 8: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Operator Precedence

Operator Descriptionlambda Lambda expressionif – else Conditional expressionor Boolean ORand Boolean ANDnot x Boolean NOT

in, not in, is, is not, <, <=, >, >=, <>, !=, == Comparisons, including membership tests and identity tests,

| Bitwise OR^ Bitwise XOR& Bitwise AND<<, >> Shifts+, - Addition and subtraction

*, /, //, % Multiplication, division, remainder

+x, -x, ~x Positive, negative, bitwise NOT

** Exponentiation

x[index], x[index:index], x(arguments...), x.attribute Subscription, slicing, call, attribute reference

8

Page 9: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Operators

Examples x + y is the sum of x and y x – y is the difference of x and y x * y is the product of x and y x / y is the quotient of x and y x // is the floored quotient of x and y (integer division) x % y is the remainder of x / y x ** y is x raised to the power y -x is x negated +x is x

Page 10: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Notes on some of the Arithmetic Operators

The / operator performs floating point division. It returns a float even if both the numerator and denominator are ints.

The // operator performs integer division. When the result is positive, the result is truncated. When the result is negative, the // operator truncates

downward. This doesn’t always return an integer. If either the

numerator or denominator is a float, it will be a float.

10

Page 11: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Coercion

Rule: the operands of a binary operator must have the same type.

Question: are the following allowed? x = 3.2 + 3 y = 18 – 3.1

Whenever both arguments to an operand are of different built-in numeric type, the narrower type is coerced to the wider. x = 3.2 + 3 y = 18 – 3.1

11

Page 12: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Examples

What are the following values and types 1 / 2 1 % 2 10 % 3 32 / 4 32 // 4 32.0 / 4.0 10.0 // 4.0 3.2 ** 2

Page 13: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Casting

You can programmatically make computed values into different types float(2) int(2.0) int(-2.5) float(3//2)

http://www.flickr.com/photos/84338444@N00/3779270029/sizes/z/in/photostream/

13

Page 14: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Math Library

Computing with numbers is common. Common functions related to mathematics are collected into a library of functions known as the math library. In order to use these functions, must import the

library using import math

The math library includes the functions shown on the following slids

14

Page 15: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Numeric and Representation

math.ceil(x). Return the ceiling of x, the smallest integer greater than or equal to x. math.copysign(x, y). Return x with the sign of y. copysign(1, -0.0) returns -1.0. math.fabs(x). Return the absolute value of x. math.factorial(x). Return x factorial. Raises ValueError if x is not integral or is negative. math.floor(x). Return the floor of x, the largest integer less than or equal to x. math.fmod(x, y. )Return fmod(x, y), as defined by the platform C library. Note that the

Python expression x % y may not return the same result. Function fmod() is generally preferred when working with floats, while Python’s x % y is preferred when working with integers.

math.frexp(x). Return the mantissa and exponent of x as the pair (m, e). m is a float and e is an integer such that x == m * 2**e exactly.

math.fsum(iterable). Return an accurate floating point sum of values in the iterable. math.isinf(x). Checks if the float x is positive or negative infinite. math.isnan(x). Checks if the float x is a NaN (not a number). NaNs are part of the IEEE

754 standards. Operation like but not limited to inf * 0, inf / inf or any operation involving a NaN, e.g. nan * 1, return a NaN.

math.ldexp(x, i). Return x * (2**i). This is essentially the inverse of function frexp(). math.modf(x). Return the fractional and integer parts of x. Both results carry the sign

of x and are floats. math.trunc(x). Return the Real value x truncated to an Integral (usually an integer).

15

Page 16: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Power, Logarithmic, Trigonometric

math.exp(x). Return e**x. math.log(x[, base]). Return the logarithm of x to the given base. If the base is not specified, return the

natural logarithm of x (that is, the logarithm to base e). math.log1p(x). Return the natural logarithm of 1+x (base e). The result is calculated in a way which is

accurate for x near zero. math.log10(x). Return the base-10 logarithm of x. math.pow(x, y). Return x raised to the power y. pow(1.0, x) and pow(x, 0.0) always return 1.0, even

when x is a zero or a NaN. If both x and y are finite, x is negative, and y is not an integer then pow(x, y) is undefined, and raises ValueError

math.sqrt(x). Return the square root of x. math.acos(x). Return the arc cosine of x, in radians. math.asin(x). Return the arc sine of x, in radians. math.atan(x). Return the arc tangent of x, in radians. math.atan2(y, x). Return atan(y / x), in radians. The result is between -pi and pi. math.cos(x). Return the cosine of x radians. math.hypot(x, y). Return the Euclidean norm, sqrt(x*x + y*y). This is the length of the vector from the

origin to point (x, y). math.sin(x). Return the sine of x radians.math.tan(x)Return the tangent of x radians. math.degrees(x). Converts angle x from radians to degrees. math.radians(x). Converts angle x from degrees to radians. math.pi is the mathematical constant pi. math.e is the mathematical constant e.

16

Page 17: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Example: Quadratic Equation

Consider writing a function so solve the quadratic equation:

Note that x may have two values for a particular assignment of constants a, b and c.

Write a program that reads a, b and c as inputs. The function should produce the two solutions.

17

Page 18: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Example: Quadratic Equation

# quadratic.py# A program to compute the (real) roots of a quadratic equation.# Note: this program crashes if there are no real roots# valid example: 3, 4, -2# invalid example: 1, 2, 3def main(): print("This program finds the real roots to a quadratic equation.") print()

a, b, c = eval(input("Enter coefficients a, b and c: "))

denom = 2*a discRoot = math.sqrt(b*b – 4*a*c) root1 = (-b + discRoot) / denom root2 = (-b – discRoot) / denom

print("The solutions are: ", root1, root2)

main()

18

Page 19: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Example: factorials19

As a creative musician you would like to monetize your ability by copyrighting all possible sequences of tones drawn from a 6-note instrument (say, the kazoo). How many combinations of these 6 notes are there if each note is played once

for the same duration? The answer is given by 6 factorial (or 6!). N! = N * (N-1) * (N-1) * … * 2 * 1 Write a function to read a value N from the user and compute the factorial of N.

# factorial.py# This program computes the factorial of N (N must be a positive integer)def main(): print("This program computes the factorial")

n = eval(input("Please enter a positive integer: ")) factorial = 1 for factor in range(n,1,-1): factorial = factorial * factor

print("The factorial of ", n, "is", factorial)

main()

Page 20: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Example

Consider the following infinite series: 1 + 1/1! + 1/2! + 1/3! + 1/4! + …

This series is equal to the value “e” or 2.71828… Write a program to compute the value of this series for the first N terms.

Page 21: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Numbers (again)

Not only are ints and floats supported, but so are complex values. A complex value is a point on the complex plane The imaginary unit j corresponds to the solution of: j**2 = -1 A complex number is given by two values: the real and imaginary

components. A complex value can be constructed using

3+2j complex(3, 2)

Operators support complex arithmetic (3+2j)*(5-2j) (3+2j)-complex(5,-2) (1+2j)/(1+1j)

A complex value has two attributes x = 3 + 2j x.real x.imag

Page 22: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Booleans

There is a 'bool' data type with two values True False

Three Boolean operators: or, and, not

The two binary operators are short-circuit

Expression Result

x or y if x is false then y else x

x and y if x is false then x else y

not x if x is false then True else False

Page 23: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Comparisons

There are eight comparison operations in Python. Each of these operators produces a bool.

Operator Description

a < b less than

a <= b less than or equal to

a > b greater than

a >= b greater than or equal to

a == b equal

a != b not equal

is object identity

is not negated object identity

Page 24: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Comparisons

Unlike Java, comparisons can be chained x < y <= z is equivalent to x < y and y <= z except

that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

Page 25: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Booleans

All python values have a truthiness (similar to JavaScript). Any object can be used where a Boolean is needed. The following values are "falsey" None False 0, 0.0, 0+0j Any empty sequence or map Any object that overrides methods in a certain way

The following values are "truthy" Everything not listed above

Page 26: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Examples

What are the values of the following? 1<2 and 3<5 1<2 or 5<3 5<1 or 5<2 1<2<3 "" or 2<5 "Hello" and "World" "Jim" or "Jill" [1,2,3] and [4,5,6]

Page 27: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Bitwise Operators

Bitwise operations only apply to integers. Bitwise operators apply logical operations to bits of an integer.

Operator Description

x | y bitwise or

x ^ y bitwise exclusive or

x & y bitwise and

x << n left shift

x >> n right shift

~x invert (negate)

Page 28: WHAT KIND OF THING IS IT? Python: Basic Numeric Types

Bitwise

For the bitwise operators 1 is True 0 is False

Consider the least significant three bits of an int. 5 | 13

0101

1001

1101

5 & 13

0101

1001

0001

5 >> 1

0101

0010

5 << 1

0101

1010

5 ^ 13

0101

1001

1100