≡ Menu

The square root of 2…

The square root of 2 (approximately 1.4142) is a positive real number that, when multiplied by itself, equals the number 2. 

There are a number of algorithms for approximating √2 as a ratio of integers or as a decimal. The most common algorithm for this, which is used as a basis in many computers and calculators, is the Babylonian method for computing square roots, which is one of many methods of computing square roots. It goes as follows:

First, pick a guess, a0 > 0; the value of the guess affects only how many iterations are required to reach an approximation of a certain accuracy. Then, using that guess, iterate through the following recursive computation:

\(a_{n+1}=\frac{a_{n}+\frac{2}{a_{n}}}{2}=\frac{a_{n}}{2}+\frac{1}{a_{n}}\)

In general, suppose we want to evaluate the square root of a number n. Let’s assume the \(n=a^2+b\), where \(a^2\) is the biggest square number that is less or equal to \(n\).

Then, we can write it as:

\(n-a^2=b\)

or:

\(\left( {\sqrt n + a} \right)\left( {\sqrt n – a} \right) = b \Leftrightarrow \sqrt n – a = \frac{b}{{\sqrt n + a}}\)

and then:

\(\sqrt n = a + \frac{b}{{\sqrt n + a}}\)

Recursively replacing the \(\sqrt{n}\):

\(\sqrt n = a + \frac{b}{{2a + \frac{b}{{\sqrt n + a}}}}\)

or:

For \(n=2\) we have \(a=1\) and \(b=2-1=1\). So:

In general, we will write the sequence:

\({a_{n + 1}} = 1 + \frac{1}{{{a_n} + 1}}\)

In Python:

import numpy as np
import decimal

def twoSqrt(EPS):
    decimal.getcontext().prec = 10000
    
    x = decimal.Decimal(1)
    t = x
    # while error is still big
    while abs(x*x - decimal.Decimal(2)) > EPS:
        x = decimal.Decimal(1) + decimal.Decimal(1)/(decimal.Decimal(1)+t)
        # converge the answer
        t = x
    return x

EPS = decimal.Decimal(1e-200)

r1 = twoSqrt(EPS) 
r2 = decimal.Decimal(2).sqrt()

print('%.19f' % r1)

def twoSqrt(EPS):
    decimal.getcontext().prec = 10000
    
    myList = []
    myCount = []
    
    x = decimal.Decimal(1)
    t = x
    i = 0
    myList.append(x)
    myCount.append(i)
    # while error is still big
    while abs(x*x - decimal.Decimal(2)) > EPS:
        x = decimal.Decimal(1) + decimal.Decimal(1)/(decimal.Decimal(1)+t)
        # converge the answer
        myList.append(x)
        i = i+1
        t = x
        myCount.append(i)
    plt.xlabel("iterations")
    plt.ylabel("$\sqrt{2}$ values")    
    plt.plot(myCount,myList, marker = "x")
    plt.savefig("sqrt2.jpg")
    plt.show()
    return x

With this code change, the following diagram can be obtained:

{ 0 comments }

…un campo

Vivere una vita non è attraversare un campo.

  • Boris Pasternak, da Il dottor Živago

{ 0 comments }

…le persone

La maggior parte delle persone è così stupida che davvero non è un gran complimento dire che un uomo è superiore alle media.

William Somerset Maugham, Taccuino di uno scrittore

{ 0 comments }

3D Plotting with Matplotlib

Matplotlib was originally composed with only two-dimensional plotting in mind. Around the time of the 1.0 release, some three-dimensional plotting advantages were built on top of Matplotlib’s two-dimensional layout, and the effect is handy. Three-dimensional plots are enabled by importing all necessary libraries: Numpy, matplotlib and also import axes3d from mpl_toolkits.mplot.3d:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d

Once axes3d is imported, three-dimensional axes can be developed by passing the keyword projection='3d' to any of the normal axes creation routines:

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

Let’s create the data:

xs =[1,2,3,4,5,6,7,8,9,10]
ys =[51,5,1,2,15,4,1,22,4,8]
zs =[12,43,13,23,55,37,9,11,19,10]

xt =[-1,-2,-3,-4,-5,-6,-7,8,-9,-10]
yt =[-5,-6,-2,-3,-13,-4,-1,2,-4,-8]
zt =[-2,-3,-3,-3,-5,-7,9,-11,-9,-10]

Let’s plot the Data:

ax.scatter(xs, ys, zs, c='r', marker='o')
ax.scatter(xt, yt, zt, c='b', marker='^')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
{ 0 comments }

gnuplot for dummies…

At first glance, it might seem that Gnuplot is more difficult to use for plotting than MS Excel. But it only seems that way, the entry threshold is a little higher (you can’t use a mouse to click it, you need to read the documentation here), but in practice, it comes out much easier and more convenient. I wrote a script once and have been using it all my life. It’s really much more difficult for me to plot a graph in Excel, where everything is not logical than in Gnuplot. And the main advantage of Gnuplot is that you can embed it into your programs and visualize data on the fly. Also Gnuplot without any problems builds a graph from a 30-gigabyte file of statistical data, while Exel simply crashed and could not open it.

The pluses of Gnuplot include the fact that it can be easily integrated into the code in standard programming languages. There are ready-made libraries for many languages, I personally came across Fortran and Python. Thus, you can generate graphs directly from your program.

Gnuplot — real application

There are two ways to work with Gnuplot: command mode and script execution mode. I recommend using the second mode immediately, as it is the most convenient and fastest. Moreover, the functionality is absolutely the same.

The graph is plotted by the plot command. As command parameters, you can specify a function or the name of the data file. As well as which column of data to use and how to connect the points, how to denote them, etc. Let’s illustrate.

gnuplot> plot sin(x)
Gnuplot interactive plot of sin(x) function

After executing the command, a window will open where there will be a sine graph with default signatures. Let’s improve this graph and figure out some additional options at the same time.
Let’s sign the axes.

set xlabel "X"

Specifies the label for the abscissa axis.

set ylabel "Y"

Specifies the label for the ordinate axis.

Let’s add a grid to show where the graph is built.

set grid

We will set the limits of the values to which the graph will be limited via the command

set yrange [-1.1:1.1]

Thus, the graph will be drawn from the minimum value of -1.1 to a maximum value of 1.1.

Likewise, I set the range for the abscissa so that only one period of the sinusoid is visible.

set xrange[-pi:pi]

We need to add a title to our schedule:

set title "Gnuplot's examples" font "Helvetica Bold, 20"

Note that you can set fonts and their sizes. See the Gnuplot documentation for what fonts can be used.

And finally, in addition to the sine on the graph, let’s also draw the cosine, and also set the line type and its color. And also add legends, what are we drawing.

plot sin(x) title "sin(x)" lc rgb "red", cos(x) title "cos(x)" lc rgb "green"

Here we draw two graphs on one canvas, in red and green. In general, there are a lot of options for lines (dotted line, stroke, solid), line widths, colors. Like the types of points. My goal is only to demonstrate the range of possibilities. Let’s bring all the commands into one pile and execute them sequentially.

the result:

If you honestly repeated all this after me, you might have noticed that manually entering it every time, even copying, is somehow not comme il faut. But is this a ready-made script? So let’s do it!

a gnuplot script

We make it executable and run it.

chmod +x gnuplottest.gpi

As a result, we get the same window with charts. If you don’t add -persist to the title, the window will automatically close after the script is executed.

In order to output data to a file and not to the screen, you need to reassign the terminal.

set terminal png size 800, 600
set output "result.png"
rep

As you might guess, we indicate the file type, its resolution, then we indicate the file name. Add these two lines to the beginning of our script, and we get this picture in the current folder.

Our final Gnuplot graph

In order to save to postscript, you need to use the following commands:

set terminal postscript eps enhanced color solid
set output "result.ps"
rep

In Python?

Here a simple code for plot a cosine function in Python using matplotlib:

import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0,2.0,0.01)
s = 1+ np.cos(2*np.pi*t)
plt.plot(t,s,'*')
plt.xlabel('Time(t)')
plt.ylabel('Voltage(mV)')
plt.title('Cosine wave plot(cos(x))')
plt.show()

{ 0 comments }

PyFiglet…

FIGlet – as you can read here – is a program for making large letters out of ordinary text.

A very quick note on how to add FontArt to Python’s output view.I will give a few tips on how to add FontArt to the python output display.

The method is quite easy, the first thing we have to do is install the PyFiglet library. PyFiglet converts ASCII text to ASCII art font.

pip install pyfiglet

After the installation is complete, then open the code editor and type the following code:

# You can get the type of font itself at the following link.
# http://www.figlet.org/fontdb.cgi

import pyfiglet
result = pyfiglet.figlet_format('wow', font='banner3')
print(result)

The result of the code is like this:

In addition, we can also change the displayed font, by adding a font parameter to the .figlet_format function:

# You can get the type of font itself at the following link.
# http://www.figlet.org/fontdb.cgi

import pyfiglet
result = pyfiglet.figlet_format('wow', font='colossal')
print(result)

The result of the code is like this:

Below, a complete code for the project:

import pyfiglet
import argparse

# HOW TO USE
# python asciart.py
# python asciart.py --text "Ciao"
# python asciart.py --text "Ciao" --font banner3-d

# You can see the font list here:
# http://www.figlet.org/fontdb.cgi

parser = argparse.ArgumentParser()
parser.add_argument('-t', '--text', help='text')
parser.add_argument('-f', '--font', help='font')

text = 'This is sample text'

args = parser.parse_args()
if args.text:
    text = args.text

if args.font:
    result = pyfiglet.figlet_format(text, font=args.font)
else:
    result = pyfiglet.figlet_format(text)

print(result)
{ 0 comments }