Skip to content

Implement an interval class #777

@hollasch

Description

@hollasch

A class that operates on ranges of double values. Use cases:

Here's a sketch of an interval class (not all methods below need be implemented; only those actually needed):

struct interval {
    double min, max;

    interval() : min(0), max(0) {}
    interval(double x) : min(x), max(x) {}
    interval(double _min, double _max) : min(_min), max(_max) {}

    double size() const {
        return max - min;
    }

    bool contains(double x) const {
        return min <= x && x <= max;
    }

    double clamp(double x) const {
        return (x < min) ? min
             : (x > max) ? max
             : x;
    }

    interval hull(const interval& other) const {
        return interval(std::min(min, other.min), std::max(max, other.max));
    }

    interval intersect(const interval& other) const {
        return interval(std::max(min, other.min), std::min(max, other.max));
    }

    static interval empty    = interval(+std::numeric_limits::infinity, -std::numeric_limits::infinity);
    static interval universe = interval(-std::numeric_limits::infinity, +std::numeric_limits::infinity);
}

This class could also support transforms, such as scale, translate, whatever.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions