Juval Bechar
Juval Bechar

Reputation: 23

How to fix noise in Plots [julia]

I have a function that is randomly generated by another function. my goal is to have that function generated around 10 times, and find the expected value of all them.

Here is my problem: whenever I try to plot a random function directly (by plotting it the generating function for example) it all goes perfect, but when I try to have some kind of function in the middle it all goes down the hill.


I thought that maybe, because the generated function uses some variables I declare in it, then maybe it has some kind of problem with it when you try to pass it on to the next function, but even when I avoided using variables in it it still came out wierd


the working code:

plot(generatingFunction())

the bad code:

function R(x)            
     generatingFunction()(x)
end
plot(R)

working code plot bad code plot

Upvotes: 2

Views: 62

Answers (1)

mbauman
mbauman

Reputation: 31342

Julia always evaluates its arguments before passing them to a function. Thus, when you call plot(generatingFunction()), it's the same as doing:

f = generatingFunction()
plot(f)

In contrast, when you put the creation of your function—generatingFunction()—inside another function, then Julia will create a new version every time R is called!

function R(x)
     f = generatingFunction()            
     f(x)
end
plot(R)

What you really want here is to move the creation of f outside of the evaluation of R — you can either do this as a const global or as a captured closure. A typical idiom for the latter is something like:

let
    f = generatingFunction()
    global function R(x)
        f(x)
    end
end

Upvotes: 1

Related Questions