In [1]:
function plus2(x)
x + 2
end
Out[1]:
In [11]:
function plus2(x)
return x+2
end
Out[11]:
In [3]:
f(x) = x + 2
Out[3]:
In [12]:
f = function (x) x + 2 end
Out[12]:
In [13]:
f = x -> x +2
Out[13]:
In [5]:
f(x) = 2*x
Out[5]:
In [7]:
ϕ(x) = 2*x
Out[7]:
In [4]:
2f(x) = 2*x
In [17]:
π |> sin |> exp
Out[17]:
In [18]:
(exp∘sin)(π)
Out[18]:
In [17]:
function logly(x,y=10)
log(y,x)
end
Out[17]:
In [19]:
logly(4,2)
Out[19]:
In [20]:
function logly(y=10,x)
log(y,x)
end
In [1]:
function logly(x; base=10)
log(base,x)
end
Out[1]:
In [26]:
logly(10)
Out[26]:
In [27]:
logly(8,base=2)
Out[27]:
In [2]:
logly("breakme",base=10)
In [7]:
workspace()
In [17]:
function logly(x::Real;base::Real=10)
log(base,x)
end
Out[17]:
In [18]:
logly("foo",10)
In [19]:
function logly(x::Real;base::Real=10)::Real
log(base,x)
end
Out[19]:
In [11]:
function thumbsUp(x)
x += 1
end
Out[11]:
In [12]:
x = 1;
thumbsUp(x)
x
Out[12]:
In [16]:
function multiThumbsUp(x)
x[:] += 1
end
Out[16]:
In [18]:
multiThumbsUp([0 2 2 6])
Out[18]:
In [ ]:
# convention: name of functions modifying the input should end with !
In [38]:
f(x) = 2*sin(x)-2;
In [41]:
f.([1,2,3])
Out[41]:
In [33]:
function duplicate(x)
(x,x+1)
end
Out[33]:
In [36]:
y,z = duplicate(1);z
Out[36]:
In [42]:
function f(x::Float64)
1
end
function f(x::Int64)
0
end
Out[42]:
In [44]:
f(1)
Out[44]:
In [45]:
f(1.0)
Out[45]:
In [46]:
function f(x::Float64,y::Int64)
x*y
end
function f(x::Int64,y::Float64)
x+y
end
Out[46]:
In [49]:
f(2.0,2)
Out[49]:
In [50]:
f(2,3.0)
Out[50]:
In [51]:
f(2.0,2.0)
In [2]:
# example
h(x,y) = x*y+2
Out[2]:
In [3]:
@code_native h(1,2)
In [4]:
@code_native h(1.0,2.0)
In [5]:
@code_native h(1.0,2)
Important note: The compiled code does NOT perform any type checking!
In [3]:
# view type information extracted by compiler
@code_typed h(1.0,2)
Out[3]:
In [6]:
code_native(h,(Float64,Int32))
In [10]:
code_native(h,(Int32,Int64))
In [11]:
code_llvm(h,(Int32,Int64))
In [70]:
fv(x,::Val{true}) = x+2
fv(x,::Val{false}) = x-5
Out[70]:
In [74]:
fv(1,Val(true))
Out[74]:
In [76]:
fv(1,Val(false))
Out[76]:
One options to calculate the inverse of a real number $x$ is given by the recurrence relation.
$$ y_{k+1} = 2y_k - y_k^2 x $$with sattisfies $y_{k+1} \to \frac{1}{x}$ for $k \to \infty$.
Create a function newtonInv
calculating the inverse of a given value $x$ using this iterations. The arguments of the function should be
Bonus Task: Modify the function such that it has an option "relTol" specifying a relative tolerance (default: 1e-8). Instead of performing a fixed amount of iterations, the modified function should iterate until the solution satisfies the given tolernace.