Function doesn't show result

Hello! I wrote little function but its not show output. I am fresh in this language and I’ve no idea why it’s not work.
My input is : f(x->1) after that program freezes.
This is function:

function f(func=x^2)
a_lower = 1 
b_upper = 2  
ro = (3 - sqrt(5))/2
eps = b_upper - a_lower

a_old = a_lower
b_old = b_upper
iter = 0
while(eps > 10^-5)
    a_new = a_old + (b_old - a_old)*ro 
    b_new = b_old - (b_old - a_old)*ro
    if (func(b_new) > func(a_new))
        b_old = b_new       
    elseif (func(b_new) < func(a_new))
        a_old = a_new
    eps = b_old - a_old
    iter = iter + 1


There are two issues with this function.

  1. Your function infinite loops as func(b_new) = 1 and func(a_new) = 1 so b_old and a_old will never get updated.

  2. You are print(a_new,func(a_new)) in the last line, but a_new is not in scope in here. (I’m assuming there is also an end after your whole code)

1 Like

The parameters of f seem a little odd to me, what f(func=x^2) should mean? It seems to mean that func is the sole parameter and it can be ommited, in this case, the value is the square of a global variable x?

1 Like

Welcome to the Julia forum! There are several problems with your code:

  1. the function is missing an end (please indent properly, that should help you catch those things)

  2. the func default argument x^2 is not a function, but a value (if x is in scope), perhaps you meant x -> x^2 (which is, BTW, available as abs2 in Julia)

  3. finally, for x -> 1, neither branch is called (1 < 1 is always false), so no values are changed. You can print things in a loop (see @show), or use the debugger. It may be better to just use an else anyway.