I am using ListPlot combined with Table to approximate a function. Table allows to generate equally spaced points, from a minimum and a maximum values with a specified distance. However the result of ListPlot, in approximating my function, is a collection of points which is quite continuous where the derivative of the function is almost zero and distant points where the derivative is bigger. I need a way to increase the density of points in the region where the function is varying, is there a way?
2 Answers
Here's an example that uses Plot
's built in adaptive sampling engine to generate points where they are most needed to describe more rapidly changing portions of a curve:
ClearAll[f]
f[x_] := (x - 1) (x - 3) (x - 4)
plot = Plot[f[x], {x, 0.5, 4.5}, PlotRange -> All]
We can extract the points generated by Plot
as follows and then plot them with ListPlot
:
points = First@ Cases[plot, Line[list_] :> list, All];
ListPlot[points, PlotRange -> All]
-
$\begingroup$ Thanks for this answer, this is useful. I solved my problem using Union to attach different Table with different steps and that worked. I'll try anyway to extract the points generated by the algorithm of Plot. $\endgroup$ Commented May 5, 2023 at 15:23
-
$\begingroup$ @GiancarloCreanza I encourage you to submit a self-answer then, so we can see what your problem and solution were. Self - answers are encouraged on this site. $\endgroup$– MarcoBCommented May 5, 2023 at 15:55
Your question is not specific so I try with the following idea:
list = {};
For[i = 0.1, i < 10, i += 1, AppendTo[list, i^2]];
I used $i^2$ so that there will be more points near zero and less for bigger values but you can customize you function as you wish.
-
$\begingroup$ Thanks, I will try with this code. Anyway I was searching for a way avoiding for loops. $\endgroup$ Commented May 5, 2023 at 8:36
-
$\begingroup$ Look at this question: mathematica.stackexchange.com/questions/200162/… $\endgroup$ Commented May 5, 2023 at 8:39
-
$\begingroup$ Thank you! I will try with that $\endgroup$ Commented May 5, 2023 at 8:40
-
1$\begingroup$ This fails to answer the question; which is presumably about generating more points where the slope is steep. Since the OP has not shared a minimal example (yet), I would request you to wait until a more concrete question has been presented. If such an example is not presented, then this answer might be deleted. If the question is updated and this answer is not updated, the same thing might happen. Thanks for your interest. $\endgroup$– SyedCommented May 5, 2023 at 10:45
-
$\begingroup$ The problem was exactly the one you said, but I found a solution using Union to put together more Tables with different steps, as pointed out in the link provided by @saveriopalazzi. Should I delete my answer? $\endgroup$ Commented May 5, 2023 at 11:06
Cases
. Search the site for examples of the latter. $\endgroup$