Define a Julia function

My question is about which way is better to define this function:
Way 1:

function α(x, a, b, α_0, Lmin, Lnom, Lmax)
if Lmin <= x < Lnom
return a * (x-Lnom)^2 + α_0
elseif Lnom <= x <= Lmax
return b * (x-Lnom)^2 + α_0
end
end
Way 2:
function α(x)
a, b, α_0, Lmin, Lnom, Lmax = Calculations
if Lmin <= x < Lnom
return a * (x-Lnom)^2 + α_0
elseif Lnom <= x <= Lmax
return b * (x-Lnom)^2 + α_0
end
end

As shown above, I want to define a function α(x). The other
parameters are constants. These constants are calculated outside of α(x).

  1. I want to ask for some suggestions on whether I should put these constants as
    arguments or directly put them within α(x)?
  2. I think it would be more convenient to put them inside of the function (together with related calculations). My concern is, I need to use this function to do repeated optimization. Will this slow my program (since these parameters need to be calculated)?

if you gonna repeatedly call α(x) and Calculations does calculation, then you don’t want to repeat calculation inside α(x)

1 Like

Depends on what “Calculations” are. The compiler can constant-fold some thing.

Thanks. In my case, it’s just some simple calculations like curve fitting from known points and some arithmatic calculations.
And there are some parameters in the calculation that I need to modify for different study cases, that’s why I don’t want to manually assign specific numbers in the function definition.

Thanks. Yes, that’s the case. I need to repeatedly call this function in my program.

In that case, I would define a data structure (struct) to hold the calculation results. Then write two functions: one (probably a constructor) to initialize the data structure instance d from the parameters, and another function function α(x, d). Or potentially you could make d a callable object (which often makes sense for a curve-fitting result), in which case you could write d(x).

1 Like

Thanks for the suggestions. I will try them in my program.
I just thought about simply adding the global keyword inside the function to call
these parameters.
Will this slow my program?

If the global variables you are accessing are not constants (i.e., do not have const before their name in their definition), then most surely your code will be slowed.

I see. Thanks for the reply.

It’s not just performance. Non-constant global variables in any programming language are an obstacle to software engineering in the long run. Google “why global variables bad” for lots of explanations.

2 Likes

Thanks!