Creating your own functions

| categories: python | tags:

We can combine operations to evaluate complex equations. Consider the value of the equation \(x^3 - \log(x)\) for the value \(x=4.1\).

import numpy as np
x = 3
print x**3 - np.log(x)
25.9013877113

It would be tedious to type this out each time. Next, we learn how to express this equation as a new function, which we can call with different values.

import numpy as np
def f(x):
    return x**3 - np.log(x)

print f(3)
print f(5.1)
25.9013877113
131.02175946

It may not seem like we did much there, but this is the foundation for solving equations in the future. Before we get to solving equations, we have a few more details to consider. Next, we consider evaluating functions on arrays of values.

Copyright (C) 2013 by John Kitchin. See the License for information about copying.

org-mode source

Discuss on Twitter

Advanced mathematical operators

| categories: python | tags:

The primary library we will consider is nil, which provides many mathematical functions, statistics as well as support for linear algebra. For a complete listing of the functions available, see http://docs.scipy.org/doc/numpy/reference/routines.math.html. We begin with the simplest functions.

import numpy as np
print np.sqrt(2)
1.41421356237

1 Exponential and logarithmic functions

Here is the exponential function.

import numpy as np
print np.exp(1)
2.71828182846

There are two logarithmic functions commonly used, the natural log function nil and the base10 logarithm nil.

import numpy as np
print np.log(10)
print np.log10(10)  # base10
2.30258509299
1.0

There are many other intrinsic functions available in nil which we will eventually cover. First, we need to consider how to create our own functions.

Copyright (C) 2013 by John Kitchin. See the License for information about copying.

org-mode source

Discuss on Twitter

Sorting in python

| categories: python | tags:

Matlab post

Occasionally it is important to have sorted data. Python has a few sorting options.

a = [4, 5, 1, 6, 8, 3, 2]
print a
a.sort()  # inplace sorting
print a

a.sort(reverse=True)
print a
[4, 5, 1, 6, 8, 3, 2]
[1, 2, 3, 4, 5, 6, 8]
[8, 6, 5, 4, 3, 2, 1]

If you do not want to modify your list, but rather get a copy of a sorted list, use the sorted command.

a = [4, 5, 1, 6, 8, 3, 2]
print 'sorted a = ',sorted(a)  # no change to a
print 'sorted a = ',sorted(a, reverse=True)  # no change to a
print 'a        = ',a
sorted a =  [1, 2, 3, 4, 5, 6, 8]
sorted a =  [8, 6, 5, 4, 3, 2, 1]
a        =  [4, 5, 1, 6, 8, 3, 2]

This works for strings too:

a = ['b', 'a', 'c', 'tree']
print sorted(a)
['a', 'b', 'c', 'tree']

Here is a subtle point though. A capitalized letter comes before a lowercase letter. We can pass a function to the sorted command that is called on each element prior to the sort. Here we make each word lower case before sorting.

a = ['B', 'a', 'c', 'tree']
print sorted(a)

# sort by lower case letter
print sorted(a, key=str.lower)
['B', 'a', 'c', 'tree']
['a', 'B', 'c', 'tree']

Here is a more complex sorting problem. We have a list of tuples with group names and the letter grade. We want to sort the list by the letter grades. We do this by creating a function that maps the letter grades to the position of the letter grades in a sorted list. We use the list.index function to find the index of the letter grade, and then sort on that.

groups = [('group1', 'B'),
          ('group2', 'A+'),
          ('group3', 'A')]

def grade_key(gtup):
    '''gtup is a tuple of ('groupname', 'lettergrade')'''
    lettergrade = gtup[1]

    grades = ['A++', 'A+', 'A', 'A-', 'A/B'
              'B+', 'B', 'B-', 'B/C',
              'C+', 'C', 'C-', 'C/D',
              'D+', 'D', 'D-', 'D/R',
              'R+', 'R', 'R-', 'R--']
    
    return grades.index(lettergrade)

print sorted(groups, key=grade_key)
[('group2', 'A+'), ('group3', 'A'), ('group1', 'B')]

Copyright (C) 2013 by John Kitchin. See the License for information about copying.

org-mode source

Discuss on Twitter

Unique entries in a vector

| categories: python | tags:

Matlab post

It is surprising how often you need to know only the unique entries in a vector of entries. In python, we create a “set” from a list, which only contains unique entries. Then we convert the set back to a list.

a = [1, 1, 2, 3, 4, 5, 3, 5]

b = list(set(a))
print b
[1, 2, 3, 4, 5]
a = ['a',
    'b',
    'abracadabra',
    'b',
    'c',
    'd',
    'b']

print list(set(a))
['a', 'c', 'b', 'abracadabra', 'd']

Copyright (C) 2013 by John Kitchin. See the License for information about copying.

org-mode source

Discuss on Twitter

Basic math

| categories: math, python | tags:

Python is a basic calculator out of the box. Here we consider the most basic mathematical operations: addition, subtraction, multiplication, division and exponenetiation. we use the to get the output. For now we consider integers and float numbers. An integer is a plain number like 0, 10 or -2345. A float number has a decimal in it. The following are all floats: 1.0, -9., and 3.56. Note the trailing zero is not required, although it is good style.

print 2 + 4
print 8.1 - 5
6
3.1

Multiplication is equally straightforward.

print 5 * 4
print 3.1*2
20
6.2

Division is almost as straightforward, but we have to remember that integer division is not the same as float division. Let us consider float division first.

print 4.0 / 2.0
print 1.0/3.1
2.0
0.322580645161

Now, consider the integer versions:

print 4 / 2
print 1/3
2
0

The first result is probably what you expected, but the second may come as a surprise. In integer division the remainder is discarded, and the result is an integer.

Exponentiation is also a basic math operation that python supports directly.

print 3.**2
print 3**2
print 2**0.5
9.0
9
1.41421356237

Other types of mathematical operations require us to import functionality from python libraries. We consider those in the next section.

Copyright (C) 2013 by John Kitchin. See the License for information about copying.

org-mode source

Discuss on Twitter
« Previous Page -- Next Page »