06.09.2021 Views

First Semester in Numerical Analysis with Julia, 2020a

First Semester in Numerical Analysis with Julia, 2020a

First Semester in Numerical Analysis with Julia, 2020a

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 1. INTRODUCTION 21<br />

Us<strong>in</strong>g anonymous functions we can manipulate arrays easily. For example, suppose<br />

we want to pick the elements of an array that are greater than 0. This can be done<br />

us<strong>in</strong>g the function filter together <strong>with</strong> an anonymous function x->x>0.<br />

In [44]: filter(x->x>0,[-2,3,4,5,-3,0])<br />

Out[44]: 3-element Array{Int64,1}:<br />

3<br />

4<br />

5<br />

The function count is similar to filter, but it only computes the number of elements<br />

of the array that satisfy the condition described by the anonymous function.<br />

In [45]: count(x->x>0,[-2,3,4,5,-3,0])<br />

Out[45]: 3<br />

Types<br />

In <strong>Julia</strong>, there are several types for <strong>in</strong>tegers and float<strong>in</strong>g-po<strong>in</strong>t numbers such as Int8,<br />

Int64, Float16, Float64, and more advanced types for Boolean variables, characters,<br />

and str<strong>in</strong>gs. When we write a function, we do not have to declare the type of its<br />

variables: <strong>Julia</strong> figures what the correct type is when the code is compiled. This is<br />

called a dynamic type system. For example, consider the squareit function we def<strong>in</strong>ed<br />

before:<br />

In [46]: function squareit(x)<br />

return x^2<br />

end<br />

Out[46]: squareit (generic function <strong>with</strong> 1 method)<br />

The type of x is not declared <strong>in</strong> the function def<strong>in</strong>ition. We can call it <strong>with</strong> real or<br />

<strong>in</strong>teger <strong>in</strong>puts, and <strong>Julia</strong> will know what to do:<br />

In [47]: squareit(5)<br />

Out[47]: 25

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!