Post No. 12.25i: And Now Let’s Explore Irrational Numbers

Hello everybody,

Michael here, and today for my 150th post I thought I’d do something a little different. This time, something with a broader scope-irrational nnumbers in programming. This isn’t my first broad post (after all, I did Colors in Programming in November 2021) but hey, what better time for a broad post than my 150th overall post (did anyone catch the little detail in the post title hinting that this is the 150th post?).

But first, a little bit on irrational numbers

What are irrational numbers? You’ve likely heard of them if you’ve at least taken pre-algebra but for those who don’t know or don’t remember, irrational numbers arre simply numbers that can’t be expressed as fractions.

What would a rational number look like? Well, think of the 10 cardinal digits from 0-9, any fraction like 1/2 or 3/4 (yes, even improper fractions count as rational numbers), and any decimal (regardless of how many decimal points it carries on for).

Now, what would an irrational number look like? I went over one of them in an earlier post-e, also known as Euler’s Number-2.71828 (check out R Lesson 30: Logarithms for more information on Euler’s number). Some other irrational numbers include imaginary numbers (like 3+2i), the square roots of all negative numbers and positive prime numbers (which in turn are imaginary), the golden ratio, and of course, PI.

Imaginary numbers are their own special type of irrational numbers-and it’s important to remember that while all imaginary numbers are irrational, not all irrational numbers are imaginary. Imaginary numbers always contains an imaginary unit i (though the letter used to represent that imaginary unity can vary-more on that later), which equals the square root of -1.

If a number has a “real” and “imaginary” part, then it is referred to as a complex number. Take the complex number 3+2i. The 3 would be the “real” part and the 2i would be the “imaginary” part. The same logic would apply for a number like 6i, which, even though it only has a single part, is still consered a complex number since it has a “real” part (a hidden 0) and an imaginary part (6i).

  • For those that haven’t heard of the golden ratio before, it’s a mathematical constant (just like PI and e) that equals approximately 1.61 that is often considered as an “aesthethically pleasing” number as it can be found in fields such as art, nature, and photography (just to name a few).

Imaginary numbers in programming

Now that we’ve discussed the basics of what irrational numbers are all about, let’s explore how they’re used in programming.

First off, let’s see how imaginary numbers work in programming! Here’s an example of simple arthemic with imaginary numbers in Python:

print(3+5j*2)
(3+10j)

As you can see, Python is capabale of simple arithmetic with imaginary numbers (and is likely capabale of far more complex mathematics too). Also notice how Python uses a j to represent an imaginary unit instead of an i. Watch what happens when you try to use an i in this expression:

print(3+5i*2)

File "<ipython-input-5-f1daeb22835b>", line 1
    print(3+5i*2)
             ^
SyntaxError: invalid syntax

Trying to use i for the imaganiary unit will give you an error in this expression.

Now let’s take a look at how imaginary numbers are used in other programming languages! Here are two examples of expressions with imaginary numbers in R:

(3i+4)*(2i-2)
[1] -14+2i

(7i+3)-2
[1] 1+7i

As you can see, R-just like Python-performs simple imaginary number arithmetic quite well. One interesting quirk with R is that, no matter how I list the imaginary number in my expression (whether in the form of real part+imaginary part or imaginary part+real part), the output always displays in the form of real part+imaginary part.

Other irrational numbers in programming

Now that we briefly explored imaginary numbers in programming, let’s turn our attention to other irrational numbers!

Here’s an example in Python showing how to obtain irrational, non-imaginary numbers-e, the golden ratio, and pi.

from scipy import constants

from scipy import constants

print(constants.golden)
print(constants.pi)
print(constants.e)

1.618033988749895
3.141592653589793
1.602176634e-19

In case you ever wanted to use pi, the golden ratio (denoted by scipy.constants.golden) or e in any Python calculation, you now know the easy way to access these irrational numbers-just use the from scipy import constants line to access the scipy constants package and then use the line scipy.constants.[number you wish to use] to access the irrational number.

If that seems cool, here are some other constants the scipy.constants package contains (and there are far too many to mention for this entry):

from scipy import constants

print(constants.year)
print(constants.day)
print(constants.hour)

31536000.0
86400.0
3600.0

These are just a few of the time constants that the scipy.constants module contains-and in case your wondering why year gave you such a large number, it’s because these time constants are stored in seconds (yes, a year contains 31,536,000 seconds). The same logic applies as to why day and hour give you seemingly odd large numbers.

  • In case you’re wondering what the SciPy package is, first of all, it stands for scientific Python. The SciPy package is built upon the numpy package and contains various helpful mathematical and scientific functions and modules (like the constants module we just discussed).
  • Let me know if you all would like to see a SciPy series of lessons!

Now that we know how to obtain these irrational, non-imaginary numbers in Python, let’s see them used in computations!

print(constants.golden*3)
print(constants.pi**2)
print(constants.e/100)

4.854101966249685
9.869604401089358
1.6021766339999998e-21

Not gonna lie, Python’s computations of these mathematical constants work like a charm!

Now to explore these irrational, non-imaginary numbers in another programming language! I know, let’s try Java!

import java.lang.Math;

public class Numbers {


    public static void main(String[] args) {
        long product = (long) (Math.E*6);
        long sum = (long) (Math.PI+12);
        
        System.out.println(product);
        System.out.println(Math.PI);
        System.out.println(Math.E);
        System.out.println(sum);
        
    }
    
}

16
3.141592653589793
2.718281828459045
15

As you can see, Java can be a bit trickier than R or Python when it comes to working with irrational numbers (after all, there are more imports necessary-plus the need to cast any expression with these irrational numbers into type long)!

Another thing you’ll notice with Java is that in it’s Math class, PI and E are the only irrational number constants built-in to the class. The golden ratio isn’t built in, but you can easily define it. Here’s how you’d do so in Java:

long golden = (long) (1+Math.sqrt(5)/2)

And here’s what that number would look like in the output:

2

For some odd reason, if I use a long for my golden ratio in Java, I get a 2 in return (even though the approximation of the golden ratio equals 1.61).

Thanks for reading these past 12.25i posts. Here’s to the next 12.25i!

Michael

R Lesson 31: Logarithmic Graphs

Hello everybody,

Michael here, and today’s lesson will be a sort-of contiuation of my previous post on R logarithms (R Lesson 30: Logarithms). However, in this post, I’ll cover how to create logarithmic graphs in R.

Let’s begin!

Two types of log plots

There are two main types of logarithmic plots in R-logarithmic scale plots and log-log plots.

What do these log plots do, exactly? Well, in the case of the logarithmic scale plot, only one of the plot’s axes uses a logarithmic scale while the other maintains a linear scale while with the log-log plot both axes use logarithmic scales.

When would you use each type of plot? In the case of logarithmic scale plots, you’d use them for analyses such as exponential growth/decay or percentage changes over a period of time. As for the log-log plots, they’re better suited for analyses such as comparative analyses (which involve comparing datasets with different scales or units) and data where both the x-axis and y-axis have a wide range of values.

And now for the logarithmic scale plots!

Just as the header says, let’s create a logarithmic scale plot in R!

Before we begin, let’s be sure we have the necessary data that we’ll use for this analysis-

This dataset is simpler than most I’ve worked with on this blog, as it only contains 11 rows and two columns. Here’s what each column means:

  • Date-the date that the bitcoin mining reward will be halved
  • Reward-the amount of bitcoin you will recieve after a successful mining as of the halving date.

For those unfamiliar with basic Bitcoin mining, the gist of the process is that when you mine Bitcoin you get a reward. However, after every 3-4 years, the reward for mining bitcoin is halved. For instance, on the first ever day that you could mine bitcoin (January 1, 2009), you would be able to recieve 50 bitcoin (BTC) for a successful haul. In 2012, the reward was halved to 25 BTC for a successful haul. The next halving is scheduled to occur in Spring 2024, where the reward will be halved to 3.125 BTC. Guess bitcoin mining isn’t as profitable as it was nearly 15 years ago?

There will likely be no more Bitcoin left to mine by the year 2140, so between now and then, the Bitcoin mining reward will get progressively smaller (a perfect example of exponential decay). I did mention that the Bitcoin mining reward will be less than 1 BTC by the year 2032.

  • I mean, don’t take my word for it, but maybe the supply of mineable bitcoin won’t run out by 2140 and the reward instead would get progressively smaller until it’s well over 1/1,000,000,000th of 1 BTC. Just my theory though :-).

Now, enough about the Bitcoin mining-let’s see some logarithmic scale plots! Take a look at the code below.

First, we’ll read in our dataset:

bitcoin <- read.csv("C:/Users/mof39/OneDrive/Documents/bitcoin halving.csv", encoding="utf-8")

Next, we’ll create our logarithmic scale plot! Since there is only one axis that will use a log-scale (the y-axis in this case), let’s remember to specify that

plot(bitcoin$Date, bitcoin$Reward, log = "y", pch = 16, col = "blue", xlab = "Year", ylab = "BTC Reward")

Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
2: In min(x) : no non-missing arguments to min; returning Inf
3: In max(x) : no non-missing arguments to max; returning -Inf

If we tried to use the plot() function along with all the parameters specified here, we’d get this error-Error in plot.window(...) : need finite 'xlim' values. Why does this occur?

The simple reason we got the error is because we used a column with non-numeric values for the x-axis. How do we fix this? Let’s create a numeric vector of the years in the Reward column (with the exception of 2009, all of the years in the Reward column are leap years until 2080) and use that vector as the x-axis:

years <- c(2009, 2012, 2016, 2020, 2024, 2028, 2032, 2036, 2040, 2044, 2048, 2052, 2056, 2060, 2064, 2068, 2072, 2076, 2080)

plot(years, bitcoin$Reward, log = "y", pch = 16, col = "red", xlab = "Year", ylab = "BTC Reward", main = "BTC Rewards 2009-2080")

Voila! As you can see here, we have a nice log-scale plot showing the exponential decay in bitcoin mining rewards from 2009 to 2080.

How did create this nice-looking plot? Well, we set the value of the log parameter of the plot() function equal to y, as we are only creating a log-scale plot. If we wanted to create a log-log plot, we would se the value of the log parameter to xy, which would indicate that we would use a logarithmic scale for both the x and y axes.

As for the rest of the values of the parameters in the plot() function, keep them the same as you would for a normal, non-logarithmic R scatter plot (except of course adapting your x- and y-axes and title to fit the scatterplot).

Now, one thing I did want to address on this graph is the scale on the y-axis, which might look strange to you if you’re not familiar with log-scale plots. See, the plot() function’s log parameter in R uses base-10 logs by default, and in turn, the y-axis will use powers of 10 in the scale (the scientific notation makes the display a little neater). For instance, 1e+01 represents 10, 1e+00 represents 0, and so on. Don’t worry, all the data points in the dataset were plotted correctly here.

And now, let’s create a log-log plot

Now that we’ve created a log-scale plot, it’s time to explore how to create a log-log plot in R!

loglog <- data.frame(x=c(2, 4, 8, 16, 32, 64), y=c(3, 9, 27, 81, 243, 729))

plot(loglog$x, loglog$y, log = "xy", pch = 16, col = "red", xlab = "Power of 2", ylab = "Power of 3", main = "Sample Log-Log Plot")

In this example, I created the dataframe loglog and filled both axes with powers of 2 and 3 to provide a simple way to demonstrate the creation of log-log plots in R.

As for the plot() function, I made sure to set the value of the log parameter to xy since we’re creating a log-log plot and thus need both axes to use a logarithmic scale. Aside from that, remember to change the plot’s axes, labels, and titles as appropriate for your plot.

Now, you might’ve noticed somthing about this graph. In R, both log-log and log-scale plots utilize base-10 logs for creating the plot. However, you likely noticed that the scale for the log-scale plot displays its values using scientific notation and powers of 10. The scale (or should I say scales) for the log-log plot doesn’t use scientifc notation and powers of 10 to display its values. Rather, the log-log plot uses conventional scaling to display its values-in other words, the scale for the log-log plot bases its values of the range of values in both axes rather than a powers-of-10 system. Honestly, I think this makes sense since the plot is already using a logarithmic scale for both axes, which would make the whole powers-of-10 thing in the scale values redundant.

  • Of course, if you want to change the scale displays in either the log-log or log-scale plots, all you would need to do is utilize the axis() function in R after creating the plot. Doing so would allow you to customize your plot’s axis displays to your liking.

Thnaks for reading!

Michael