001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.numbers.angle;
018
019import java.util.function.DoubleUnaryOperator;
020
021/**
022 * Reduces {@code |a - offset|} to the primary interval {@code [0, |period|)}.
023 *
024 * Specifically, the {@link #applyAsDouble(double) computed value} is:
025 * {@code a - |period| * floor((a - offset) / |period|) - offset}.
026 */
027public class Reduce implements DoubleUnaryOperator {
028    /** Offset. */
029    private final double offset;
030    /** Period. */
031    private final double period;
032
033    /**
034     * Create an instance.
035     *
036     * @param offset Value that will be mapped to {@code 0}.
037     * @param period Period.
038     */
039    public Reduce(double offset,
040                  double period) {
041        this.offset = offset;
042        this.period = Math.abs(period);
043    }
044
045    /** {@inheritDoc} */
046    @Override
047    public double applyAsDouble(double x) {
048        final double xMo = x - offset;
049        return xMo - period * Math.floor(xMo / period);
050    }
051}