≡ Menu

Python Crash Course…

Libraries

Python is a high-level open-source language. But the Python world is inhabited by many packages or libraries that provide useful things like array operations, plotting functions, and much more. We can import libraries of functions to expand the capabilities of Python in our programs.

OK! We’ll start by importing a few libraries to help us out. First: our favorite library is NumPy, providing a bunch of useful array operations (similar to MATLAB). We will use it a lot! The second library we need is Matplotlib, a 2D plotting library which we will use to plot our results.

import numpy as np
from matplotlib import pyplot as plt

We are importing one library named numpy (that we will call np)and we are importing a module called pyplot (we refer to this library as plt) of a big library called matplotlib. To use a function belonging to one of these libraries, we have to tell Python where to look for it. For that, each function name is written following the library name, with a dot in between. So if we want to use the NumPy function linspace(), which creates an array with equally spaced numbers between a start and end, we call it by writing:

import numpy as np
from matplotlib import pyplot as plt

myarray = np.linspace(0,5,10)
print(myarray)

Variables

Python doesn’t require explicitly declared variable types like Fortran and other languages.

a =5      #a is an integer
b= 'Five' #b is a string
c = 5.0   #c is a floating point number

print(type(a))
print(type(b))
print(type(c))

we have:

Note: if you divide an integer by an integer that yields a remainder, the result will be converted to a float.

Whitespace in Python

Python uses indents and whitespace to group statements together. To write a short loop in Fortran, you might use:

b= "Five"

do i = 1, 5
    print(b)
end do

Python does not use end do blocks like Fortran, so the same program as above is written in Python as follows:

b= 'Five' #b is a string

for i in range(5):
    print(b)

If you have nested for-loops, there is a further indent for the inner loop.

for i in range(3):
    for j in range(3):
        print(i, j)
    
    print("This statement is within the i-loop, but not the j-loop")

Slicing Arrays

In NumPy, you can look at portions of arrays in the same way as in Matlab, with a few extra tricks thrown in. Let’s take an array of values from 1 to 5.

vec = np.array([1, 2, 3, 4, 5])

print(vec)

Python uses a zero-based index, so let’s look at the first and last element in the array vec

print(vec)
print(vec[0], vec[4])

it has this output:

[1 2 3 4 5]
1 5

Arrays can also be ‘sliced‘, grabbing a range of values. Let’s look at the first three elements:

vec = np.array([1, 2, 3, 4, 5])

print(vec)
print(vec[0], vec[4])
print(vec[0:3])

Note here, the slice is inclusive on the front end and exclusive on the back, so the above command gives us the values of vec[0], vec[1] and vec[2], but not vec[3].

Assigning Array Variables

One of the strange little quirks/features in Python that often confuses people comes up when assigning and comparing arrays of values. Here is a quick example. Let’s start by defining a 1-D array called vecx:

vecx = np.linspace(1,5,5)
print(vecx)

The linspace command return evenly spaced numbers over a specified interval. In this case, for vecx we have:

[1. 2. 3. 4. 5.]

OK, so we have an array vecx, with the values 1 through 5. I want to make a copy of that array, called vecy, so I’ll try the following:

vecy = vecx
print(vecy)

and we have:

[1. 2. 3. 4. 5.]

Great. So vecx has the values 1 through 5 and now so does vecy. Now that I have a backup of vecx, I can change its values without worrying about losing data (or so I may think!).

vecx[2]=10
print(vecx)
print(vecy)

we have:

And that’s how things go wrong! When you use a statement like vecx=vecy, rather than copying all the values of vecx

into a new array called vecy, Python just creates an alias (or a pointer) called vecy and tells it to route us to vecx. So if we change a value in vecx then vecy will reflect that change (technically, this is called assignment by reference).

If you want to make a true copy of the array, you have to tell Python to copy every element of vecx into a new array. Let’s call it vecz:

vecx = np.linspace(1,5,5)
print(vecx)

vecy = vecx
vecz=vecx.copy()

vecx[2]=10

print(vecx)
print(vecy)
print(vecz)

Matrix Multiplication

A matrix is a 2D array, where each element in the array has 2 indices. For example, [[1, 2], [3, 4]] is a matrix, and the index of 1 is (0,0).

We can prove this using Python and Numpy.

import numpy as np
A = [[1, 2], [3, 4]]
     
print(np.array(A)[0,0])

The simple form of matrix multiplication is called scalar multiplication, multiplying a scalar by a matrix.

Scalar multiplication is generally easy. Each value in the input matrix is multiplied by the scalar, and the output has the same shape as the input matrix.

In Python:

import numpy as np

b=7
A = [[1, 2], [3, 4]]

C=np.dot(b,A)
print(np.array(C))

There are a few things to keep in mind.

  1. Order matters now. \(A \times B \neq B \times A\);
  2. Matrices can be multiplied if the number of columns in the 1st equals the number of rows in the 2nd;
  3. Multiplication is the dot product of rows and columns. Rows of the 1st matrix with columns of the 2nd.

Let’s replicate the result in Python.

import numpy as np

A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
C = np.dot(A,B)
print(np.array(C))

Inner product

The inner product takes two vectors of equal size and returns a single number (scalar). This is calculated by multiplying the corresponding elements in each vector and adding up all of those products. In numpy, vectors are defined as one-dimensional numpy arrays.

To get the inner product, we can use either np.inner() or np.dot(). Both give the same results. The inputs for these functions are two vectors and they should be the same size.

import numpy as np

# Vectors as 1D numpy arrays
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

print("a= ", a)
print("b= ", b)
print("\ninner:", np.inner(a, b))
print("dot:", np.dot(a, b))

Transpose

The transpose of a matrix is found by switching its rows with its columns. We can use np.transpose() function or NumPy ndarray.transpose() method or ndarray.T (a special method which does not require parentheses) to get the transpose. All give the same output.

import numpy as np

a = np.array([[1, 2], [3, 4], [5, 6]])
print("a = ")
print(a)

print("\nWith np.transpose(a) function")
print(np.transpose(a))

print("\nWith ndarray.transpose() method")
print(a.transpose())

print("\nWith ndarray.T short form")
print(a.T)

Trace

The trace is the sum of diagonal elements in a square matrix. There are two methods to calculate the trace. We can simply use the trace() method of an ndarray object or get the diagonal elements first and then get the sum.

import numpy as np

a = np.array([[2, 2, 1],
               [1, 3, 1],
               [1, 2, 2]])

print("a = ")
print(a)
print("\nTrace:", a.trace())
print("Trace:", sum(a.diagonal()))

Rank

The rank of a matrix is the dimensions of the vector space spanned (generated) by its columns or rows. In other words, it can be defined as the maximum number of linearly independent column vectors or row vectors.

The rank of a matrix can be found using the matrix_rank() function which comes from the numpy linalg package.

import numpy as np

a = np.arange(1, 10)
a.shape = (3, 3)

print("a = ")
print(a)
rank = np.linalg.matrix_rank(a)
print("\nRank:", rank)

Determinant

The determinant of a square matrix can be calculated det() function which also comes from the numpy linalg package. If the determinant is 0, that matrix is not invertible. It is known as a singular matrix in algebra terms.

import numpy as np

a = np.array([[2, 2, 1],
               [1, 3, 1],
               [1, 2, 2]])

print("a = ")
print(a)
det = np.linalg.det(a)
print("\nDeterminant:", np.round(det))

True inverse

The true inverse of a square matrix can be found using the inv() function of the numpy linalg package. If the determinant of a square matrix is not 0, it has a true inverse.

import numpy as np

a = np.array([[2, 2, 1],
               [1, 3, 1],
               [1, 2, 2]])

print("a = ")
print(a)
det = np.linalg.det(a)
print("\nDeterminant:", np.round(det))
inv = np.linalg.inv(a)
print("\nInverse of a = ")
print(inv)

Flatten

Flatten is a simple method to transform a matrix into a one-dimensional numpy array. For this, we can use the flatten() method of an ndarray object.

import numpy as np

a = np.arange(1, 10)
a.shape = (3, 3)

print("a = ")
print(a)
print("\nAfter flattening")
print("------------------")

print(a.flatten())

Eigenvalues and eigenvectors

Let A be an n x n matrix. A scalar \(\lambda\) is called an eigenvalue of A if there is a non-zero vector x satisfying the following equation.

\(A x=\lambda x\)

The vector x is called the eigenvector of A corresponding to \(\lambda\).

In numpy, both eigenvalues and eigenvectors can be calculated simultaneously using the eig() function.

import numpy as np

a = np.array([[2, 2, 1],
               [1, 3, 1],
               [1, 2, 2]])

print("a = ")
print(a)

w, v = np.linalg.eig(a)

print("\nEigenvalues:")
print(w)
print("\nEigenvectors:")
print(v)

The sum of eigenvalues (1+5+1=7) is equal to the trace (2+3+2=7) of the same matrix! The product of the eigenvalues (1x5x1=5) is equal to the determinant (5) of the same matrix!

{ 0 comments }

How to generate and read QR Code in Python

QR code is a type of matrix barcode that is machine readable optical label which contains information about the item to which it is attached. In practice, QR codes often contain data for a locator, identifier, or tracker that points to a website or application, etc.

Problem Statement :

Generate and read QR codes in Python using qrcode and OpenCV libraries

Installing required dependencies:

pyqrcode module is a QR code generator. The module automates most of the building process for creating QR codes. This module attempts to follow the QR code standard as closely as possible. The terminology and the encoding used in pyqrcode come directly from the standard.

pip install pyqrcode

Install an additional module pypng to save image in png format:

pip install pypng

Import Libraries

import pyqrcode
import png
from pyqrcode import QRCode
import cv2
import numpy as np

Create QR Code:

# OUTPUT SECTION

# String which represents the QR code
s = "https://www.raucci.net"

# output file name

filename = "qrcode.png"

# Generate QR Code

img = pyqrcode.create (s)

# Create and save the svg file naming "brqr.svg"

img.svg("brqr.svg", scale=8)

# Create and save the svg file naming "brqr.png"

img.png("brqr.png", scale=6)
qr code file named brqr.png

Read QR Code

Here we will be using OpenCV for that, as it is popular and easy to integrate with the webcam or any video.

# INPUT SECTION

# read the QRCODE image

img = cv2.imread('brqr.png')

# initialize the cv2 QRCode detector
detector = cv2.QRCodeDetector()

val, pts, st_code=detector.detectAndDecode(img)

print(val)

Here the output

The output of code
{ 0 comments }

…a very simple integral

Here I want to show how to compute an integral to prove that \(\pi\) is not equal to \(22/7\) at all.

Consider the following integral:

\(\int\limits_0^1 {\frac{{{x^4}{{\left( {1 – x} \right)}^4}}}{{1 + {x^2}}}{\text{d}}x} \)

This may look somewhat difficult, but it actually works out to be quite simple to solve. I am going to solve this integral in what I believe to be the most pedestrian way. By this I mean that I am not going to use any clever tricks or substitutions, but instead will base my solution off methods that anyone who has taken any level of Calculus course should be able to follow.

The first thing I will do is to convert the function \((x^4(1-x)^4)/(1+x^2)\) into a polynomial (with a remainder) and thus simplify my integral.

We have:

\({\left( {1 – x} \right)^4} = {x^4} – 4{x^3} + 6{x^2} – 4x + 1\)

So:

\({x^4}{\left( {1 – x} \right)^4} = {x^8} – 4{x^7} + 6{x^6} – 4{x^5} + {x^4}.\)

We now want to divide this new expression by \(1+x^2\) to obtain a new expression for our function to integrate.

it is simple to verify that:

So:

Thinking back to your calculus classes you might recognize this final integral:

\(\int {\frac{1}{{1 + {x^2}}}{\text{d}}x} = {\tan ^{ – 1}}\left( x \right) + c\)

and so

The final thing to note is that our integral looked at the function \((x^4(1-x)^4)/(1+x^2)\) for x between 0 and 1. This function, as you can see from the following plot, is allways positive

Thus, we must have that

\(0 < \int\limits_0^1 {\frac{{{x^4}{{\left( {1 – x} \right)}^4}}}{{1 + {x^2}}}} {\text{d}}x = \frac{{22}}{7} – \pi \)

or, in other words:

\(\pi < \frac{{22}}{7}.\)

{ 0 comments }

Estimating Pi…

We will be exploring a very interesting, and simple for that matter, application of statistics to help us estimate the value of Pi.

For this method, we will be imagining a simple scenario. Imagine for a moment, that we have the unit circle, inside a square.

Unit circle inside a square

By having the unit circle, we immediately figure out that the area of the square will be four since the radius of the circle is defined at one, which means that our square will have sides with a value of two. Now here’s where things get interesting, if we take the ratio of both of areas, we end up getting the following:

\(\frac{{{A_c}}}{{{A_s}}} = \frac{{\pi {r^2}}}{{{{\left( {2r} \right)}^2}}} = \frac{\pi }{4}\)

Both of these geometric figures end up having a ratio of pi over four between them, which is an important value for our next step in which we use a bit of imagination.

from “Ordine e disordine” by Luciano De Crescenzo

For a moment, imagine that you have a circle inside a square on the ground; suppose it starts raining. Some drops will most likely fall inside the circle and others will likely fall inside the square but outside the circle. Using this concept is how we will code our estimator pi, throwing some random numbers into the unit circle equation, as shown below:

\(x^2+y^2=1\)

Furthermore, taking a ratio of throws that landed inside our circle and the total number of throws, we can then formulate the following:

\(\frac{{N{\text{of throws inside circle}}}}{{N {\text{of total throws}}}} = \frac{{{N_C}}}{{{N_T}}}\)

And by combining our ratio between the unit circle with the square with this new equation, we can assume the next equation

\(\frac{{{N_C}}}{{{N_T}}} \simeq \frac{\pi }{4} \Leftrightarrow \frac{{4{N_C}}}{{{N_T}}} \simeq \pi \)

With this equation, we can finally start coding our estimator and see how close we can get to pi’s actual value.

The code

import matplotlib.pyplot as plt
import numpy as np
import time as t
from progress.bar import Bar


tin = t.time()


# numeri di punti della simulazione
n=80000

# Vettore coordinate  x e y dei punti casuali
x = np.random.rand(n)
y = np.random.rand(n)

Pi_Greco = np.zeros(n)
#Vettore distanza

d= (x**2 + y**2)**(1/2)

Ps = 0
Pq = 0

bar = Bar('Processing', max=n)

for i in range(n):
	Pq = Pq + 1
	if d[i] < 1:
		Ps = Ps+1
	Pi_Greco [i] = 4*(Ps/Pq)
	bar.next()

bar.finish()

Pi_Greco_Reale = np.ones(n)*np.pi

tfin = t.time()

print('Valore di Pi Greco: ', 4*Ps/Pq)
print('elapsed time: ', round(tfin-tin, 3))

plt.figure(1)
plt.plot(Pi_Greco, 'red', label='estimate of Pi')
plt.plot(Pi_Greco_Reale, 'green', label='Exact value')

plt.xlabel('throws')
plt.ylabel('value')
plt.title('Monte Carlo simulation')


plt.legend()
plt.show()
Results for our pi estimation. Pi is represented by the green line, while red represents our estimations.

It’s quite interesting to see our estimation start with low accuracy but as we increase our attempts, we start to get a convergence on the the value of pi, as shown by our green line. Statistical methods like this, and other more complex versions, are nice tools to understand and experiment within the world of physics. I highly recommend taking a look into some Statistical Mechanic concepts to see the beauty behind the application of statistics and probability in physics, and maybe take some time play with these concepts in Python!

{ 0 comments }

Python animations with Matplotlib

In Python, plotting graphs is straightforward — you can use powerful libraries like Matplotlib. It happens, however, that you need to visualize the trend over time of some variables – that is, you need to animate the graphs.

Luckily, it’s just as easy to create animations as it is to create plots with Matplotlib.

Matplotlib

Matplotlib – as you can read on the official site – is a comprehensive library for creating static, animated, and interactive visualizations in Python. You can plot interactive graphs, histograms, bar charts, and so on.

How to Install Matplotlib

Installing Matplotlib is simple. Just open up your terminal and run:

pip install matplotlib

Numpy

Also, if you don’t have numpy, please install it so you can follow the examples in this tutorial:

pip install numpy

How to Plot with Matplotlib

Even though this tutorial is about animations in Matplotlib, first let’s create a simple static graph of a sine wave:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 10, 0.1)
y = np.sin(x)

fig = plt.figure()
ax = plt.axes(xlim=(0, 10), ylim=(-1.1, 1.1))
diagram = plt.plot(x, y)
 
plt.show()
A basic sine wave

How to Animate with Matplotlib

To create an animation with Matplotlib you need to use Matplotlib’s animation framework’s FuncAnimation class.

For instance, let’s create an animation of a sine wave:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation

fig = plt.figure()
ax = plt.axes(xlim=(0, 5), ylim=(-1.5, 1.5))
line, = ax.plot([], [], lw=2)

def init():
    line.set_data([], [])
    return line,

def animate(i):
    x = np.linspace(0, 5, 500)
    y = np.sin(2 * np.pi * (x + 0.02 * i))
    line.set_data(x, y)
    return line,

sinewawe_animation = FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True)
sinewawe_animation.save("Animation.gif")

plt.show()

We have:

Let’s then go through the code above in a bit more detail to better understand how animations work with Matplotlib.

Lines 1–3

Here you add the required libraries. In particular, we add the FuncAnimation class that can be used to create an animation for you.

Lines 5–7

fig = plt.figure()
ax = plt.axes(xlim=(0, 5), ylim=(-1.5, 1.5))
line, = ax.plot([], [], lw=2)

Here you first create an empty window for the animation figure. Then you create an empty line object. This line is later modified to form the animation.

Lines 9–11

def init():
    line.set_data([], [])
    return line,

Here you create an init() function that sets the initial state for the animation.

Lines 13–17

You then create an animate() function. This is the function that gives rise to the sine wave. It takes the frame number i as its argument, then it creates a sine wave that is shifted according to the frame number (the bigger it is, the more the wave is shifted). Finally, it returns the updated line object. Now the animation framework updates the graph based on how the line has changed.

def animate(i):
    x = np.linspace(0, 5, 500)
    y = np.sin(2 * np.pi * (x + 0.02 * i))
    line.set_data(x, y)
    return line,

Line 19

sinewawe_animation = FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True)

This line of code puts it all together and creates the actual animation object. It simply:

  • Renders an animation to the figure fig by repeatedly calling the animate() function starting from the initial state defined by init()
  • The number of frames rendered to “one round of animation” is 200.
  • A delay between two frames is 20 milliseconds (1000ms / 20ms = 50 FPS).
  • (The blit=True makes sure only changed pieces of the plot are drawn, to improve the efficiency)

Line 21

sinewawe_animation.save("Animation.gif")

This piece of code is used to generate an animated gif (the same one I used in this tutorial to show you the animation)

Line 22

You guessed it — this line shows the animation.

{ 0 comments }

Palindromic numbers…

A palindrome – as you can read here from wikipedia – is a word, number, phrase, or other sequence of characters which reads the same backward as forward, such as madam or racecar.

A curious series of palindromic numbers is obtained by multiplying by themselves numbers composed of strings of 1 (the 1’s must be at least two to have a product that has more than one digit):

The series of palindromes ends here. If you get to ten 1’s per factor, the product is no longer a palindrome:

The reason why the series is interrupted at ten digits has to do with the ordering by columns of the partial products of the multiplications. The addition of partial products is performed by shifting each subsequent row by one column to the left. This determines first the increase and then the decrease of the sums that generate the final product. As long as the 1’s in the column are at most nine, the mechanism works:

But if the 1’s in one column become ten, then carrying 1 to the next column breaks the symmetry and prevents the product of the multiplication from being a palindrome number.

{ 0 comments }

L’anima la si ha ogni tanto. Nessuno la ha di continuo e per sempre. Giorno dopo giorno, anno dopo anno possono passare senza di lei. A volte nidifica un po’ più a lungo sole in estasi e paure dell’infanzia. A volte solo nello stupore dell’essere vecchi. Di rado ci da una mano in occupazioni faticose, come spostare mobili, portare valigie o percorrere le strade con scarpe strette. Quando si compilano moduli e si trita la carne di regola ha il suo giorno libero. Su mille nostre conversazioni partecipa a una, e anche questo non necessariamente, poiché preferisce il silenzio. Quando il corpo comincia a dolerci e dolerci, smonta di turno alla chetichella. È schifiltosa: non le piace vederci nella folla, il nostro lottare per un vantaggio qualunque e lo strepito degli affari la disgustano. Gioia e tristezza non sono per lei due sentimenti diversi. È presente accanto a noi solo quando essi sono uniti. Possiamo contare su di lei quando non siamo sicuri di niente e curiosi di tutto. Tra gli oggetti materiali le piacciono gli orologi a pendolo e gli specchi, che lavorano con zelo anche quando nessuno guarda. Non dice da dove viene e quando sparirà di nuovo, ma aspetta chiaramente simili domande. Si direbbe che così come lei a noi, anche noi siamo necessari a lei per qualcosa.

Wisława Szymborska, da Qualche parola sull’anima.

{ 0 comments }

A (apparently) simple problem …

So when I say a simple mathematical problem most would think that I am kidding but I am not, there are many unsolved mathematical problems in the world but this is so simple but yet unsolved.

The problem is called “3n + 1 problem” or “Collatz conjecture”. To understand the problem first we need to understand what it is, so basically just pick natural number if the number is odd then we mutiple the number with 3 and add 1, if the number is even we divide it by 2. We apply these conditions to resultant value. in other words:

In modular arithmetic notation, define the function f as follows:

{\displaystyle f(n)={\begin{cases}{\frac {n}{2}}&{\text{if }}n\equiv 0{\pmod {2}}\\[4px]3n+1&{\text{if }}n\equiv 1{\pmod {2}}.\end{cases}}}

Now form a sequence by performing this operation repeatedly, beginning with any positive integer, and taking the result at each step as the input at the next.

The Collatz conjecture is: This process will eventually reach the number 1, regardless of which positive integer is chosen initially.

To demonstrate the problem let’s consider a number 5; since it is odd we apply 3n+1:

\(3 \cdot 5 + 1 = 16\left( {{\text{even}}} \right);16/2 = 8;8/2 = 4;4/2 = 2;2/2 = 1\)

So we get a value of one but we apply conditions fruther we will be stuck in loop which is 4, 2, 1.

This video sums up the problem well

If the conjecture is false, it can only be because there is some starting number which gives rise to a sequence that does not contain 1. Such a sequence would either enter a repeating cycle that excludes 1, or increase without bound. No such sequence has been found.

Since I am from engineering background here is the Python code for Collatz conjecture:

def collatz(n):
    while n > 1:
        print(n, end=' ')
        if (n % 2):
            # n is odd
            n = 3*n + 1
        else:
            # n is even
            n = n//2
    print(1, end='')
 
 
n = int(input('Enter n: '))
print('Sequence: ', end='')
collatz(n)

The above code is the demonstration of Collatz conjecture…

{ 0 comments }

The Ramanujan Summation…

Srinivasa Aiyangar Ramanujan

Ramanujan summation – as you can read from Wikipedia – is a technique invented by the mathematician Srinivasa Ramanujan for assigning a value to divergent infinite series. Although the Ramanujan summation of a divergent series is not a sum in the traditional sense, it has properties that make it mathematically useful in the study of divergent infinite series, for which conventional summation is undefined.

According to Ramanujan, if you add all the natural numbers, that is 1, 2, 3, 4, and so on, all the way to infinity, you will find that it is equal to -1/12. Yup, -0.08333333333.

\( \xi \left( { – 1} \right) = 1 + 2 + 3 + 4 + \ldots = – \frac{1}{{12}}\)

Don’t believe me? Keep reading to find out how I prove this, by proving two equally crazy claims:

\(1 – 1 + 1 – 1 + 1 – 1 + \ldots = 1/2 \) \(1 – 2 + 3 – 4 + 5 – 6 + \ldots = 1/4\)

First off, the bread and butter. This is where the real magic happens, in fact the other two proofs aren’t possible without this.

I start with a series, A, which is equal to 1–1+1–1+1–1 repeated an infinite number of times. I’ll write it as such:

\(A = 1 – 1 + 1 – 1 + 1 – 1 + \ldots \)

We can write, now:

\(1 – A = 1 – \left[ {1 – 1 + 1 – 1 + 1 – 1 + \ldots } \right]\)

so, we have:

\(1-A=A\)

and then:

\(A=\frac{1}{2}.\)

This little beauty is Grandi’s series, called such after the Italian mathematician, philosopher, and priest Guido Grandi.

Now, let to prove that:

\(1 – 2 + 3 – 4 + 5 – 6 + \ldots = 1/4\)

We start the same way as above, letting the series B =1–2+3–4+5–6⋯. Then we can start to play around with it. This time, instead of subtracting B from 1, we are going to subtract it from A. Mathematically, we get this:

\(A – B = \left( {1 – 1 + 1 – 1 + 1 – 1 + \ldots } \right) – \left( {1 – 2 + 3 – 4 + 5 – 6 + \ldots } \right)\)

and then:

\(A – B = \left( {1 – 1 + 1 – 1 + 1 – 1 + \ldots } \right) – 1 + 2 – 3 + 4 – 5 + 6 – \ldots \)

Then we shuffle the terms around a little bit, and we see another interesting pattern emerge.

\(A – B = \left( {1 – 1} \right) + \left( { – 1 + 2} \right) + \left( {1 – 3} \right) + \left( { – 1 + 4} \right) + \left( {1 – 5} \right) + \left( { – 1 + 6} \right) + \ldots \) \(A – B = 0 + 1 – 2 + 3 – 4 + 5 + \ldots \)

Once again, we get the series we started off with, and from before, we know that A = 1/2, so we use some more basic algebra and prove our second mind blowing fact of today.

\(A – B = B \Leftrightarrow A = 2B \Rightarrow 1/2 = 2B \Leftrightarrow B = 1/4\)

And voila! This equation does not have a fancy name, since it has proven by many mathematicians over the years while simultaneously being labeled a paradoxical equation. Nevertheless, it sparked a debate amongst academics at the time, and even helped extend Euler’s research in the Basel Problem and lead towards important mathematical functions like the Riemann Zeta function.

Now for the icing on the cake, the one you’ve been waiting for, the big cheese. Once again we start by letting the series C = 1+2+3+4+5+6⋯, and you may have been able to guess it, we are going to subtract C from B.

\(B – C = \left( {1 – 2 + 3 – 4 + 5 – 6 + \ldots } \right) – 1 – 2 – 3 – 4 – 5 – 6 – \ldots \)

Because math is still awesome, we are going to rearrange the order of some of the numbers in here so we get something that looks familiar, but probably wont be what you are suspecting.

\(B – C = \left( {1 – 1} \right) + \left( { – 2 – 2} \right) + \left( {3 – 3} \right) + \left( { – 4 – 4} \right) + \ldots \)

and then,

\(B – C = 0 – 4 + 0 – 8 + 0 – 12 + \ldots = – 4 – 8 – 12 – \ldots \)

At this point, we can write:

\(B-C=-4(1+2+3+\ldots)\)

that is to say

\(B-C=-4C\)

and finally

\(B=-3C\)

And since we have a value for B=1/4, we simply put that value in and we get our magical result:

\(C=-1/12\)

or, in other words:

\( \xi \left( { – 1} \right) = 1 + 2 + 3 + 4 + \ldots = – \frac{1}{{12}}\)

Now, why this is important… Well for starters, this result is used in string theory. More. The Ramanujan Summation also has had a big impact in the area of general physics – specifically in the solution to the phenomenon know as the Casimir Effect. Hendrik Casimir predicted that given two uncharged conductive plates placed in a vacuum, there exists an attractive force between these plates due to the presence of virtual particles bread by quantum fluctuations. In Casimir’s solution, he uses the very sum we just proved to model the amount of energy between the plates. And there is the reason why this value is so important.

{ 0 comments }