Learning to program (i) – a simple program in Julia

Let’s say we wanted a program to calculate the approximate age of a tree. This can be done if you have the trees diameter, and know what its growth factor is. Of course to calculate the diameter, you would have to chop a cross-section through a tree, which may not be convenient (if you want the tree to keep standing). But the diameter can be calculated from the tree circumference, which is easy to obtain.

diameter = circumference / π

The growth factor is specific to each tree species. For example, the growth factor for a Silver Maple is 3.0, for American elms it is 4.0. So if  the circumference of a Silver Maple is 94.25 inches, then the diameter will be 30″. Then multiplying this by the growth factor gives an age of approximately 90 years. In Julia calculating this is as simple as:

d = 94.25 / pi
g = 3.0
age = d * g

Here is what it looks like in an interactive session of Julia:

It’s almost like using a calculator. The value “d” is used to store the value of the calculated diameter, and the value “g” is used to store the growth factor for Silver Maples. The age of the tree is stored in the value “age“.

At the moment, these are program snippets, and not a “cohesive” program. To make that we would have to put it in a file, and give the file a name (in this case treeage.jl). We also have to add a means of printing out the result – which means adding a println() statement.

d = 94.25 / pi
g = 3.0
age = d * g

Now we can run the program by typing:

julia treeage.jl

There we have it, a simple Julia program. There are still things missing from it, but it is a starting point.




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s