# How to calculate square/cubic root by hand?

Today, technologies make everything easy and fast for us. Sometimes, when we see the ancient marvels of engineering, we wonder: “How they designed this without computers”? And the answer is: “with knowledge, inspiration and hard work”.

However, being almost irreplaceable, computers makes us more and more adjective. Our brains become lazy and we are losing some knowledge and skills. Such is the manual calculation of root. It is so easy and elegant, so I will share it here for the sake of the good old math science.

## Square root

Lets calculate x = √a first.

By squaring both sides and moving a to the left side, we obtain the following equation:

x2a = 0

This is an equation of type f(x) = 0 and we can solve numerically it using the Newton’s method:

1. Start with initial guess: x0. It is good to be close to the solution, so you can use the nearest exact root.
2. Calculate the next approximation of the root by the equation: x1 = x0f(x0)/f′(x0)
3. Continue the iterations by using the previous result to estimate a new one:
xn+1 = xnf(xn)/f′(xn).
4. Stop when you reach the desired precision.

In the above formulas, f(x) is the function and f′(x) is the first derivative. In our case:

f(x) = x2a

f′(x) = 2x

If we substitute the above equations into the Newton’s iterative formula, we get:

xn+1 = xn − (xn2a)/2xn

xn+1 = (xn + a/xn)/2

Now, lets use it to calculate √a = ?, for a = 5.

We will start with an initial guess of x0 =√4 = 2.

1st iteration: x1 = (x0 + a/x0)/2 = (2 + 5/2)/2 = 2.25

2nd iteration: x2 = (x1 + a/x1)/2 = (2.25 + 5/2.25)/2 = 2.2361

3rd iteration: x3 = (x2 + a/x2)/2= (2.2361 + 5/2.2361)/2 = 2.2361

After the second iteration, we have 5 correct significant digits, which is quite sufficient for most cases.

## Cubic root

We will use the same approach, as follows:

f(x) = x3a

f′(x) = 3x2

xn+1 = xn − (xn3a)/3xn2

xn+1 = (2xn + a/xn2)/3

Lets see how it works for 3√7. Our initial guess is: x0 = 3√8 = 2.

1st iteration: x1 = (2x0 + a/x02)/3 = (2·2 + 7/22)/3 = 1.9167

2nd iteration: x2 = (2x1 + a/x12)/3 = (2·1.9167 + 7/1.91672)/3 = 1.9129

3rd iteration: x3 = (2x2 + a/x22)/3 = (2·1.9129 + 7/1.91292)/3 = 1.9129

Again, we managed to find it after two iterations. We can also use Calcpad to create a tiny program for that:

It is interesting that just after 4 iterations, the Newton’s method finds 16 correct significant digits which is the limit precision for most computers. We also calculated the root by three different methods which give the same result.

# What’s new in Calcpad, version 5.6.3?

Since version 5.6 was released, we made some little, but nice and useful improvements. They were driven mostly by our small and dedicated GitHub community. Some of the most important changes are listed below:

## 1. Autorun mode

When enabled, the results are refreshed automatically each time you edit the code and leave the current line. You can switch it on and off by the checkbox over the output window. When the “Autorun” is off, the program displays “Quick help” on the right as before. You can run calculations by pressing the respective button. However, new shortcuts were added to make that easier. Press F5 to run the calculations and F4 to compile to input form. Ctrl + Enter calculates the results and scrolls the output to match the current line.

## 2. Scroll enhancements

After recalculation, the scroll position of the output window is preserved and not moved to the beginning as before. However, if you get lost, you can double click on a line in the source code and the output will scroll to match. Alternatively, you can press Ctrl + Enter.

## 3. New symbols

The Symbol toolbar was extended with the full set of Greek letters. You can also change the case by pressing the button on the right.

There is also a shortcut to convert Latin to Greek letters. You can use it to insert Greek letters even faster. Just type the corresponding Latin letter and press Ctrl + G. The following conversion table is used:

Some special symbols were also added: ” ø “, “Ø”, ” ° “, “∡” and primes: ” ′ “, ” ″ “, ” ‴ “, ” ⁗ “. You can now use them in variable and function names. However, you cannot start a name with a number of prime symbol. Although primes look similar to quotes, they are different characters. So, there is no danger for the program to confuse them and start a comment.

## 4. Bugs and errors

There was a problem with recognition of inches (in) units in Complex mode that is now fixed. The “i” character was parsed as the imaginary symbol first and “n” dropped out as invalid unit.

Rewriting of non-metric (Imperial and USCS) units was also improved. For example, in the previous versions, lbf/in^2 was rewritten as kPa by default. Now, ksi is used instead. It is the same with other mechanical units.

Some rare bugs were luckily identified and fixed as well. For example, if you attempted plotting with identical limits, the program fell in infinite loop.

Debugging of Calcpad programs was made easier. Links to the respective lines in the source code were added to the error messages in the output. Also nice background highlighting was implemented.

Notepad++ is one of the most popular and free text/code editors. It supports many different programming and scripting languages. You can also edit HTML, XML, CSS, JSON and other types of files. Currently, its text editing capabilities significantly exceeds those of the Calcpad own editor. Some features that worth mentioning are:

• multiple file tabs;
• predefined and custom styles;
• column editor;
• auto completion;
• bracket matching;
• line operations/sorting;
• tab/white space management;
• content folding, etc.

And and last but not least – syntax highlighting. Unfortunately, the Calcpad language is not natively supported by Notepad++. However, there is an option to add a custom language with user defined syntax (UDL). Then, you can export it as an xml file and import it everywhere else.

The good news is that we have already created the required language definition files, so you can use them to write Calcpad programs with Notepad++.

To use Notepad++ as Calcpad code editor you need to the following:

3. Unzip the archive in the preferred folder. You will find two files inside:
– Notepad++.xml – for light mode and
– Notepad++dark.xml – for dark mode.
5. Click the “Import…” button in the dialog that will appear.
6. Browse for the one of the xml files above and click “Open“.

From now on, each time you open a .cpd file, it will be automatically displayed with the Calcpad syntax highlighting. For best results with the dark theme, select the appropriate style from the “Style Configurator” dialog.

You can find it in the “Settings” menu. For example, a good option is the Twillight theme. You can also set a nice monotype font, such as “Noto Mono“, “Liberation Mono“, “Source Code Pro“, “Consolas“. etc. You can also make the whole interface t dark, by checking “Enable dark mode” in the “Preferences” dialog from the same menu.

You can also make possible to run the Calcpad programs directly from inside the Notepad++ editor. For that purpose, you will have to install the Franco Stellari’s RunMe plugin for Notepad++. You can find detailed instructions in this file: install.txt. It will add a small button at the end of the Notepad++ toolbar . Click the button or press Shift+F5 to run the current program.

.

# How to plot the Julia Set

In the previous post we discussed the Mandelbrot set. There is another beautiful algebraic fractal, called Julia set 𝓙. It is named after the French mathematician Gaston Julia, who has discovered. It is obtained by the same formula as the Mandelbrot Set:

zn+1 = zn2 + c

The difference is that z0 = x + yi is the current point (x, y) in the complex plane and c is a fixed complex number, while for the Mandelbrot set z0 = 0 and c = x + yi.

Both sets are closely related. There are a lot of different Julia sets, corresponding to different values of c. Their shapes and properties depend on where the point is located, related to the Mandelbrot set 𝓜. Inside 𝓜, the corresponding Julia set 𝓙 is connected. Outside 𝓜, it falls apart into a set of isolated points, called Fatou set 𝓕. Further away, it turns into Fatou dust – infinite number of points with zero area, similarly to the Cantor dust.

For simple plotting, you can use the following code:

```"Julia set
'Define the function
JuliaSet(z; c) = \$Repeat{z = z^2 + c @ i = 1 : n}
#hide
'Set the plotting parameters
PlotStep = 1','PlotWidth = 600','PlotHeight = 400
#show
'Plot for'c = -0.4 + 0.59i'and'n = 200'iterations
\$Map{abs(JuliaSet(x + 1i*y; c))) @ x = -1.5 : 1.5 & y = -1 : 1}
```

When you run it inside Calcpad, you will get the following result:

To obtain better and colorful images, we will use different approach this time. We will modify the JuliaSet function in a way to return directly the number of iterations for which the result overpasses 2. The source code is provided bellow:

```"Julia set
J(z; c; n) = abs(\$Repeat{z = if(abs(z) < 2; z^2 + c; 4) @ i = 1 : n})
JuliaSet(z; c) = \$Find{J(z; c; x) - 2 @ x = 1 : n}
#hide
PlotStep = 1','PlotWidth = 600','PlotHeight = 400','Precision = 10^-6
#show
'Plot for'c = -0.4 + 0.6i'and'n = 100'iterations
\$Map{JuliaSet(x + 1i*y; c)) @ x = -1.5 : 1.5 & y = -1 : 1}
```

It runs a little bit slower, but the result is worth the wait:

You can download Calcpad for free and experiment by yourself with different values of c. For example, the lightning image bellow is a special case of Julia set for c = i and is called “dendrite” fractal.

# Plotting the Mandelbrot Set

Calcpad has an interesting and undocumented feature, that I am going to reveal in this post. You can use it to quickly plot the Mandelbrot set. This is a set of complex numbers c, for which the iterative equation zn+1 = zn2 + c does not go to infinity. The most beautiful part is that it shows fractal behavior at its boundaries. If you plot it with the appropriate colors, you can create stunning images and animations. I really like those on the Maths Town’s YouTube channel:

Usually, such videos are created by complicated software, specially developed for that purpose. However, you can also plot the Mandelbrot set with Calcpad and a few lines of code. There are two ways to do that. The first one is to use the Calcpad capabilities for complex arithmetic, as follows:

```"Mandelbrot set
'Define the function
MandelbrotSet(z; c) = \$Repeat{z = z^2 + c @ i = 1 : n}
#hide
'Set the plotting parameters
PlotStep = 1','PlotWidth = 500','PlotHeight = 500
#show
'Plot for'n = 50'iterations
\$Map{abs(MandelbrotSet(0; x + 1i*y)) @ x = -1.5 : 0.5 & y = -1 : 1}
```

Open Calcpad, switch to “complex”mode, paste the above code inside, and run the calculations. You will get the following result:

It is not too bad, but still not very impressive. At least, the exterior is missing any colors. Then, how we can do the coloring? Theoretically, it is satisfied for all numbers in the set that |zn| < 2 for any n. Outside, the process diverges and the modulus goes to infinity, as n increases. You can use that in the following way:
1. For each point, calculate the number of iterations n, where |zn| gets larger than 2.
2. Map these values to colors.
3. Plot the colors at the respective coordinates.

If you play with the number of iterations n in the above example, you will see that the plot changes. The shaded area is where |zn| converges for the respective n.

If you combine the above plots and apply some colors, you can get really beautiful artistic image like the one bellow:

The only problem with this method is that it is slow and elaborate. That is why, I included a special function Mandelbrot(x; y) in Calcpad. It calculates the number of iterations, needed for the modulus to overpass 2. You can plot this function directly with the preferred color scale:

To do that, I used even shorter piece of code:

```"Mandelbrot set
#hide
'Set the plotting parameters
PlotStep = 1','PlotWidth = 500','PlotHeight = 500
#show
'Plot for'n = 50'iterations
\$Map{Mandelbrot(x; y) @ x = -1.5 : 0.5 & y = -1 : 1}
'Plot for'n = 70'iterations
\$Map{Mandelbrot(x; y) @ x = -0.59 : -0.58 & y = 0.55 : 0.56}
```

Here you can find the C# code of the Mandelbrot function that works inside Calcpad:

```        private static readonly double Log2Inv = 1 / Math.Log(2);
//Calculates the number of iterations for which z = z^2 + c satisfies |z| > 2
//Then transforms it to a smooth log scale and returns the result
protected static double MandelbrotSet(double x, double y)
{
//Checks if the point is inside the set and directly returns NaN
if (x > -1.25 && x < 0.375)
{
if (x < -0.75)
{
if (y > -0.25 && y < 0.25)
{
double x1 = x + 1,
y2 = y * y,
x2 = x1 * x1;
if (x2 + y2 <= 0.0625)
return double.NaN;
}
}
else if (y > -0.65 && y < 0.65)
{
double x1 = x - 0.25,
y2 = y * y,
q = x1 * x1 + y2;
if (q * (q + x1) <= 0.25 * y2)
return double.NaN;
}
}
//For all other points performs detailed calculations
double re = x, im = y;
for (int i = 1; i <= 1000; ++i)
{
double reSq = re * re,
imSq = im * im,
sumSq = reSq + imSq;
//To avoid the sqrt function, the check |z| > 2 is replaced by z^2 > 4
if (sumSq > 4)
{
var logZn = Math.Log(sumSq) / 2;
var nu = Math.Log(logZn * Log2Inv) * Log2Inv;
return (1.01 - Math.Pow(i - nu, 0.001)) * 1000;
}
//Calculates z = z^2 + c
im = 2 * re * im + y;
re = reSq - imSq + x;
}
return double.NaN;
}
}
```

The complete source code is available on GitHub.

# New version 5.6!

We are proud to present the new version 5.6 of the Calcpad software. It is much faster than the previous versions and includes a lot of new features.

Calcpad is ported to the latest Microsoft .NET 6.0 platform, which is faster than .NET Framework 4.x we used before. On the other side, the Calcpad code was significantly optimized. Now, we use expression trees to pre-compile parts of code that are repeatedly executed – bodies of functions, methods etc.

We also implemented better algorithms for numerical analysis. For example, we replaced the adaptive Simpson’s method for numerical integration with the adaptive Lobatto quadrature proposed by Gander and Gautschi. We adopted this algorithm for the C# language. We also developed an improved version of Anderson and Bjorks‘s root finding algorithm. That is why Calcpad 5.6 runs 3-4 times faster than 3.x versions in general and over 20 times faster when numerical methods are involved.

For plotting, we introduced adaptive interpolation of functions. It provides smooth graphs with the minimum number of calculation points. They are distributed unequally, depending on the function curvature as shown on the following figure.

Output formatting was also improved in respect to variable substitution and units of measurement. Speed of units arithmetic was also enhanced by optimizing memory consumption. That is how we reduced the pressure on the Garbage Collector.

There are also some improvements in the UI layer. Recent file list was introduced in version 5.0. Behaviour of the Undo function was improved. Support for Open Office or Libre Office was added alternatively to MS Word. Thanks to the wkhtmltopdf project, now we have direct export to pdf.

And last, but not at least, we added a lot of new and useful functions as follows:

Since version 5.0:

• new factorial operator “!”;
• log_2(x) – binary logarithm function;
• cbrt (x) – cubic root;
• root(x; n) – n-th root;
• csc(x) – cosecant;
• sec(x) – secant;
• csch(x) – hyperbolic cosecant;
• sech(x) – hyperbolic secant;
• acsc(x) – inverse cosecant;
• asec(x) – inverse secant;
• acsch(x) – inverse hyperbolic cosecant;
• asech(x) – inverse hyperbolic secant;
• acoth(x) – inverse hyperbolic cotangent;

Since version 5.6:

• min(x; y; z…) – minimum of multiple values;
• max(x; y; z…) – maximum of multiple values;
• sum(x; y; z…) – sum of multiple values;
• sumsq(x; y; z…) – sum of squares;
• srss(x; y; z…) – square root of sum of squares;
• average(x; y; z…) – average of multiple values;
• product(x; y; z…) – product of multiple values;
• mean(x; y; z…) – geometric mean;
• switch(<cond1>; <value1>; <cond2>; <value2>; …; <default>) – selective evaluation;
• take(n; a; b; c…) – returns the n-th element from the list;
• line(x; a; b; c…) – linear interpolation for variable x;
• spline(x; a; b; c…) – Hermite spline interpolation for variable x;

You can use the “take” function to represent vector and matrix-like behaviour. With the “line” and “spline“, you can interpolate over tabular data. Double interpolation is also possible with just a few line of code. If you have a function that is slow and heavy to calculate, you can use spline interpolation to speed up you program. Just sample the function in a few points and interpolate among them. We will discuss this in the next posts.

Enjoy!

# Calcpad is free and open source!

In December, 2021 Calcpad joined the big family of open source software. It is now distributed under the MIT License. The source code is available on both SourceForge and GitHub.

We welcome any contributors that could help improving the software or developing more useful features. The next big challenge is to add vectors and matrices.

# Even more 3D effects

In the last version I improved the 3D plot shading and added some nice 3D effects. Bellow is the plot of the function

f(x; y) = cos(x) + cos(y) + cos(x·y/3)/2 + cos(√(x2 + y2)·2)/2

with the “Rainbow” color scale and the “Shadows” option on: What is new is the specular light effect (the little shiny reflections). I also replaced the Gouraud shading procedure with the Phong one. It improved the image quality  without any noticeable impact on the speed (surprisingly). Since the light is distant and the view is isometric, I use the Blinn–Phong shading model. Instead of calculating the reflection vector for each vertex, it calculates the halfway vector between the viewer and light-source. It is performed once for the whole model, and that is why it is faster.

In general, there is additional overhead for generating the Html output, converting the image to base64 and rendering the Html into the “Output” window. However, as long as it takes much less than a second for all of it, the speed is not of a big concern.

Most people consider math boring, but sometimes it can be really beautiful. Recently I found some unusual application of Calcpad – to draw nice pictures using math formulas. In general, you can plot functions of two variables using the \$Map command:

`\$Map{f(x;y) @ x = a : b & y = c : d}`

I notices that you can get nice effects using the following types of functions:

`f(x;y) = abs(cos(p1(x;y)) + cos(p2(x;y)) ...)`

It creates families of intersecting curves that from canyons with hills in between. If you select “none” for the color scale, it creates nice and smooth pictures with shadows only. Bellow are some examples: f(x;y) = abs(cos(x^2/10) + cos(y^2/10)) f(x;y) = abs(cos(x + y/3) + cos(x*y/7)) f(x;y) = abs(cos(x – sin(y)) + cos(y – sin(x))) f(x;y) = abs(cos(r(x;y)*e^(ξ*r(x;y)))*e^(-1.5*ξ*r(x;y))) f(x;y) = abs(cos(r(x;y)) + cos(y)) f(x;y) = abs(cos(x) + cos((y/4)^2)) f(x;y) = abs(cos(2*r(x;y)) + cos(x) + cos(y)) f(x;y) = abs(cos(2*r(cos(x/2);cos(y/2)))) f(x;y) = abs(r(cos(x/2);cos(y/2)))

In the above equations, r(x;y) = sqr(x^2 + y^2).

The new and enhanced version of Calcpad 3.2 was released. Besides other improvements, we added some nice visual effects for 2D plotting.

In general, you can use Calcpad to plot functions of two parameters f(x; y), by the \$Map command:

`\$Map{f(x;y) @ x = a : b & y = c : d}`

The result is displayed as a 2D contour map. For example, let us take the function:

`f(x; y) = cos(x) + cos(y) + cos(π/2*sqr(x^2 + y^2))`

The \$Map command will produce the following image:

The left one is without shadow effects. Different values of the function are represented by the respective colors. Blues are the lowest and reds are the highest. However, you need to have quite a rich imagination to figure out how the surface actually looks. That is why we added a 3D shadows effects. On the right side, you can see the same image, but with shadows. The light here comes from North-West direction. Now it looks much more natural and it is easier for the human eye to perceive the shape.

The shading is calculated using the dot product of the normal vector to the surface by the vector of the light.

There are also other plotting options available: You can select among different color scales:

If you select “smooth” (gradient) scale, you will get the following image: Instead of having contours, now the colors flow smoothly from one to another. That is because the color of each pixel is calculated individually based on its value.