cetz-package / cetz-plot

Create Plots and Charts with CeTZ
GNU Lesser General Public License v3.0
50 stars 2 forks source link

Optimize sample-fn #44

Open sky126 opened 1 month ago

sky126 commented 1 month ago

Optimize sample-fn to make the curve smoother sample-fn

#let sample-fn3(fn, domain, samples, sample-at: ()) = {
  assert(samples + sample-at.len() >= 2,
    message: "You must at least sample 2 values")
  assert(type(domain) == array and domain.len() == 2,
    message: "Domain must be a tuple")

  let (lo, hi) = domain

  let y0 = (fn)(lo)
  let is-vector = type(y0) == array
  if not is-vector {
    y0 = ((lo, y0), )
  } else {
    y0 = (y0, )
  }

  let pts = (lo,)
  let currentX = lo
  let lastX = lo
  let currentY = (fn)(lo)
  let lastY = (fn)(lo)
  let i = 0
  while i < 1e4 {
    i = i + 1
    if currentX - lastX > 1e-2 or  currentY - lastY > 1e-2 {
      pts.push(currentX)
      lastX = currentX
      lastY = currentY
    }
    currentX = currentX + 1e-4 * (hi - lo)
    currentY = (fn)(currentX)
  }
  pts.push(hi)

  return pts.map(x => {
    if is-vector {
      (fn)(x)
    } else {
      (x, (fn)(x))
    }
  })
}
johannes-wolf commented 1 month ago

Thank you!

jamesrswift commented 1 month ago

10k iterations?

johannes-wolf commented 1 month ago

We could allow passing a custom sample-fn to plot.add & friends, or set a default one using set-style.