Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6207847
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T05:42:17+00:00 2026-05-24T05:42:17+00:00

Given a list of {x,y} datapoints, return a pure function f (from the reals

  • 0

Given a list of {x,y} datapoints, return a pure function f (from the reals to the reals) such that f[x]==y for every {x,y} in the data. If x is not one of the x-values then return the y-value for the previous point (the one with x-value less than x). If the function gets a value less than that of the first x-value in the data — i.e., there is no previous point — then return 0.

For example, given data {{1,20}, {2,10}}, return a pure function that looks like this:

Graph of the function given {{1,20},{2,10}} http://yootles.com/outbox/so/piecewise.png

I wrote something using Function and Piecewise that I’ll include as an answer but it seems like it might be inefficient, especially for a large list of points.
[UPDATE: My answer may actually be decent now. I’ll probably go with it if no one has better ideas.]

To be clear, we’re looking for function that takes a single argument — a list of pairs of numbers — and returns a pure function.
That pure function should take a number and return a number.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T05:42:18+00:00Added an answer on May 24, 2026 at 5:42 am

    Hand-Coded Binary Search

    If one is willing to sacrifice conciseness for performance, then an imperative binary search approach performs well:

    stepifyWithBinarySearch[data_] :=
      With[{sortedData = SortBy[data, First], len = Length @ data}
      , Module[{min = 1, max = len, i, x, list = sortedData}
        , While[min <= max
          , i = Floor[(min + max) / 2]
          ; x = list[[i, 1]]
          ; Which[
              x == #, min = max = i; Break[]
            , x < #, min = i + 1
            , True, max = i - 1
            ]
          ]
        ; If[0 == max, 0, list[[max, 2]]]
        ]&
      ]
    

    Equipped with some test scaffolding…

    test[s_, count_] :=
      Module[{data, f}
      , data = Table[{n, n^2}, {n, count}]
      ; f = s[data]
      ; Timing[Plot[f[x], {x, -5, count + 5}]]
    ]
    

    …we can test and time various solutions:

    test[stepifyWithBinarySearch, 10]
    

    step plot

    On my machine, the following timings are obtained:

    test[stepify (*version 1*), 100000]      57.034 s
    test[stepify (*version 2*), 100000]      40.903 s
    test[stepifyWithBinarySearch, 100000]     2.902 s
    

    I expect that further performance gains could be obtained by compiling the various functions, but I’ll leave that as an exercise for the reader.

    Better Still: Precomputed Interpolation
    (response To dreeves’ comment)

    It is baffling that a hand-coded, uncompiled binary search would beat a Mathematica built-in function. It is perhaps not so surprising for Piecewise since, barring optimizations, it is really just a glorified IF-THEN-ELSEIF chain testing expressions of arbitrary complexity. However, one would expect Interpolation to fare much better since it is essentially purpose-built for this task.

    The good news is that Interpolation does provide a very fast solution, provided one arranges to compute the interpolation only once:

    stepifyWithInterpolation[data_] :=
      With[{f=Interpolation[
                {-1,1}*#& /@ Join[{{-9^99,0}}, data, {{9^99, data[[-1,2]]}}]
                , InterpolationOrder->0 ]}
        , f[-#]&
      ]
    

    This is blindingly fast, requiring only 0.016 seconds on my machine to execute test[stepifyWithInterpolation, 100000].

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a function that returns a comparison matrix from a given list: def
How to define a rotates function that generates all rotations of the given list?
I'm trying to implement a function in scheme that splits the given list with
I have to write a function, that returns true if a given list is
Given a list of locations such as <td>El Cerrito, CA</td> <td>Corvallis, OR</td> <td>Morganton, NC</td>
Given a list of urls, I would like to check that each url: Returns
I have a Hibernate validator that validates a field against a given list of
I am given a list of months ( TOTAL_NUM_MONTHS ) and from this list
I coded a function to enumerate all permutations of a given list. What do
I'm trying to create a query so that all items of a given list

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.