Purpose: Write array functions to solve a mathematical problem.
Prigraming in Python
Problem 6.3
Purpose: Write array functions to solve a mathematical problem.
I'm sure you have all heard of Euclidean distance. In two dimensions, the Euclidean distance between (x1, x2) and (y1, y2) is the square root of (x1-y1)2 + (x2-y2)2, or ((x1-y1)2 + (x2-y2)2)1/2. For example, the distance between (3,1) and (1,1) is ((3-1)2+(1-1)2)1/2 = 2 and the Euclidean distance between (1,1) and (0,0) is ((1-0)2+(1-0)2)1/2 ~= 1.4142.
The Euclidean norm of a vector is just its Euclidean distance to the origin, (0,0). Therefore, the Euclidean norm of (1,1) is ~= 1.4142.
This notion of Euclidean norm can easily be extended to
|x|2 = ( Σ i = 1 to n |xi|2 )1/2 = (|x1|2+|x2|2+ ... + |xn|2 )1/2
There, Σ is a shorthand for "sum," as we saw in lecture and |xi| is just the absolute value of the real number xi. By the way, this is quite common notation.
It turns out that the Euclidean norm is just one of many possible vector norms. In fact, the Euclidean norm above can easily be generalized to the p-norm, |x|p, given by
|x|p = ( Σ i = 1 to n |xi|p )1/p = (|x1|p+|x2|p+ ... + |xn|p )1/p
which is defined for p=1,2,... . In particular, p=2 yields the Euclidean norm, a.k.a. 2-norm.
Note: p and n are totally separate (n is the dimension, p is a parameter).
See also the following attchment vector norm, |x|infinity, is defined:
You may find it interesting to note that the "infinity-norm" is the limiting case of the p-norm as p goes to infinity. To see this, look at the webpage's example table. You can indeed see that as p goes from 1 to 4, the norms are approaching 3.
For this problem, you will
- Write a function that computes the vector norm |x|p. It should work for an arbitrary vector, and the integer p should be passed as a parameter. That is, the function header might look like the following, where x is a list and p is an int
def pnorm(x, p):
So, for the example above, pnorm([1, 1], 2) should return 1.4142 … And the n or dimension of [1, 1] is len([1, 1]) which is 2.
- Test your method by computing the 2-norm of (1,1). Just call it as highlighted above.
- Write another method that computes the vector norm |x|infinity, as defined at the webpage above. Again, it should work for an arbitrary vector.
- Test your methods by reproducing the table of norms for v=(1,2,3) on that webpage.
Hints:
- You may use either ** or math.pow for raising to a power.
Turn in: Name your notebook PNorm.ipynb. Comment your program. Cut and pasteYour commented program, called PNorm.java. Place your program's output (2-norm of (1,1) and table) in comments at the end of the program. Make sure your program still compiles/runs correctly with the comments in place.
Trending now
This is a popular solution!
Step by step
Solved in 2 steps