Search code examples
javamathintervalsdivide

How can I divide an interval [start,end] into n points of equal distance?


I have an interval from start to end where start and end are type double. I want to divide the interval into n points, where each two neighboring points are the same distance apart. For example:

// Given closed interval [-3.14,3.14]:
start = -3.14
end = 3.14
n = 3

// The 3 points would be:
-3.14, 0.0, 3.14

// Where the distance between each two neighboring points is 3.14

Or:

// Given left-closed, right-open interval [0,1):
start = 0
end = 1
n = 4

// The 4 points would be:
0.0, 0.25, 0.5, 0.75

// Where the distance between each two neighboring points is .25

I'm having trouble with this, appreciate any advice


Solution

  • According to the logic you have shown so far the the interval sizes are:

    • closed: (end - start) / (n - 1)
    • open one side: (end - start) / n
    • open both sides: (end - start) / (n + 1)

    The initial left point is:

    • closed on the left: start
    • open on the left: start + interval.

    All other points just add a interval on top