# Plotting two functions with dependent input function

I have defined a function:

myJ2[n_] := 1/n* Total[RandomVariate[NormalDistribution[0, 1], n]^2]


This is basically an approximation to the gaussian integral. I want to plot this and the error graph (difference between the approximation and the exact value) at the same time. Using a random variable makes this difficult. I tried this:

DiscretePlot[{myJ2[n], 1 - myJ2[n]}, {n, 1, 1000}, Filling -> None, Joined -> True]


However, this is not quite correct, since the myJ2 function is called twice and hence gives different values due to the randomness. I improved this by using:

DiscretePlot[{x, 1 - x} /. x -> myJ2[n], {n, 1, 1000}, Filling -> None, Joined -> True, PlotStyle -> {Red, Blue}]


This gives me the correct values but both in the same color. How can I get both the function and the error function displayed in two graphs or with two different colors?

Thanks

Charly

-

As I noted in an answer to another recent question, there are several different ways to generate a list that depends on an iterator index, including Table and Array. In this particular case, I think Array is more succinct. (On my machine, there seems to be a very slight speed advantage over Table, as well, but it is too small to care about for this particular problem.

data = Array[myJ2, {1000}];


It is worth knowing that arithmetic operations are Listable, so you can just write 1-data to get the second series. This is almost always the fastest (and most succinct code) to get things done, as it avoids all the loop, iterator and Map paraphernalia.

You also don't need to transpose anything. Notice I have used ListLinePlot instead of ListPlot, which removes the need to specify the Joined option.

ListLinePlot[{data, 1 - data}]


-
I somehow missed this post. I came here because someone downvoted my answer; now I guess I know why. – Mr.Wizard Oct 6 '12 at 1:11
I didn't suppose that it was. – Mr.Wizard Oct 6 '12 at 1:15
Thanks, don't know why I did not had the idea to put the results in a resultset before. Anyway, this looks exactly what I was looking for. I tried Table and Array for some more than just 1000 calcs, but the timing is always nearly the same. I'd go for Array, since it's shorter ;-) – Charly Brownian Oct 7 '12 at 11:38

You don't need to call your function twice :

data = Table[myJ2[n], {n, 1, 1000}];

ListPlot[{Transpose[{Range[1000], data}], Transpose[{Range[1000], 1 - data}]},
Filling -> None,  Joined -> True]


-
More succinct data = Table[myJ2[n], {n, 1, 1000}]; ListPlot[{data, 1 - data}, Joined -> True] – Dr. belisarius Oct 5 '12 at 22:57
Or ListPlot[Transpose[{#, 1 - #} & /@ Array[myJ2, {1000}]], Joined -> True] – Dr. belisarius Oct 5 '12 at 23:03
This one is also nice, but I'd go for the first example, since it is shorter and easier to read. Thanks anyway! – Charly Brownian Oct 7 '12 at 11:39