refactor: rename modules

Closes #75
This commit is contained in:
siujamo
2025-06-17 16:32:57 +08:00
parent 6793e90331
commit 71e7993352
79 changed files with 501 additions and 336 deletions
@@ -0,0 +1,374 @@
/*
* Copyright (C) 2024-2025 OnixByte.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.onixbyte.nums;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;
import java.util.function.BiFunction;
import java.util.function.Function;
/**
* The {@code ChainedCalcUtil} class provides a convenient way to perform chained high-precision
* calculations using {@link BigDecimal}. It allows users to perform mathematical operations such
* as addition, subtraction, multiplication, and division with customisable precision and scale.
* By using this utility class, developers can achieve accurate results and avoid precision loss
* in their calculations.
* <p>
* <b>Usage:</b>
* <pre>
* // Perform addition: 3 + 4
* BigDecimal result1 = ChainedCalcUtil.startWith(3)
* .add(4)
* .getValue();
*
* // Perform subtraction: 4 - 2
* BigDecimal result2 = ChainedCalcUtil.startWith(4)
* .subtract(2)
* .getValue();
*
* // Perform multiplication: 3 * 6
* BigDecimal result3 = ChainedCalcUtil.startWith(3)
* .multiply(6)
* .getValue();
*
* // Perform division: 6 ÷ 2
* BigDecimal result4 = ChainedCalcUtil.startWith(6)
* .divide(2)
* .getValue();
*
* // Perform division with specified scale: 13 ÷ 7 with a scale of 2
* BigDecimal result5 = ChainedCalcUtil.startWith(13)
* .divideWithScale(7, 2)
* .getValue();
*
* // Get int, long, or double results
* int intResult = ChainedCalcUtil.startWith(3)
* .add(4)
* .getInteger();
*
* long longResult = ChainedCalcUtil.startWith(4)
* .subtract(2)
* .getLong();
*
* double doubleResult = ChainedCalcUtil.startWith(6)
* .divide(2)
* .getDouble();
*
* // Get BigDecimal result with specified scale
* BigDecimal result6 = ChainedCalcUtil.startWith(13)
* .divide(7)
* .getValue(2);
* </pre>
* The above expressions perform various mathematical calculations using the
* {@code ChainedCalcUtil} class.
* <p>
* <b>Note:</b>
* The {@code ChainedCalcUtil} class internally uses {@link BigDecimal} to handle high-precision
* calculations. It is important to note that {@link BigDecimal} operations can be memory-intensive
* and may have performance implications for extremely large numbers or complex calculations.
*
* @author sunzsh
* @version 1.1.0
* @see BigDecimal
* @since 1.0.0
*/
public final class ChainedCalcUtil {
private final static Logger log = LoggerFactory.getLogger(ChainedCalcUtil.class);
/**
* Creates a {@code ChainedCalcUtil} instance with the specified initial value.
*
* @param value the initial value for the calculation
*/
private ChainedCalcUtil(Number value) {
this.value = convertBigDecimal(value, null);
}
/**
* Starts a chained calculation with the specified initial value.
*
* @param value the initial value for the calculation
* @return a {@code ChainedCalcUtil} instance for performing chained calculations
*/
public static ChainedCalcUtil startWith(Number value) {
return new ChainedCalcUtil(value);
}
/**
* Adds the specified value to the current value.
*
* @param other the value to be added
* @return a {@code ChainedCalcUtil} instance with the updated value
*/
public ChainedCalcUtil add(Number other) {
return operator(BigDecimal::add, other);
}
/**
* Adds the specified value to the current value with a specified scale before the operation.
*
* @param other the value to be added
* @param beforeOperateScale the scale to be applied before the operation
* @return a {@code ChainedCalcUtil} instance with the updated value
*/
public ChainedCalcUtil add(Number other, Integer beforeOperateScale) {
return operator(BigDecimal::add, other, beforeOperateScale);
}
/**
* Subtracts the specified value from the current value.
*
* @param other the value to be subtracted
* @return a {@code ChainedCalcUtil} instance with the updated value
*/
public ChainedCalcUtil subtract(Number other) {
return operator(BigDecimal::subtract, other);
}
/**
* Subtracts the specified value from the current value with a specified scale before
* the operation.
*
* @param other the value to be subtracted
* @param beforeOperateScale the scale to be applied before the operation
* @return a {@code ChainedCalcUtil} instance with the updated value
*/
public ChainedCalcUtil subtract(Number other, Integer beforeOperateScale) {
return operator(BigDecimal::subtract, other, beforeOperateScale);
}
/**
* Multiplies the current value by the specified value.
*
* @param other the value to be multiplied by
* @return a {@code ChainedCalcUtil} instance with the updated value
*/
public ChainedCalcUtil multiply(Number other) {
return operator(BigDecimal::multiply, other);
}
/**
* Multiplies the current value by the specified value with a specified scale before
* the operation.
*
* @param other the value to be multiplied by
* @param beforeOperateScale the scale to be applied before the operation
* @return a {@code ChainedCalcUtil} instance with the updated value
*/
public ChainedCalcUtil multiply(Number other, Integer beforeOperateScale) {
return operator(BigDecimal::multiply, other, beforeOperateScale);
}
/**
* Divides the current value by the specified value.
*
* @param other the value to divide by
* @return a {@code ChainedCalcUtil} instance with the updated value
*/
public ChainedCalcUtil divide(Number other) {
return operator(BigDecimal::divide, other);
}
/**
* Divides the current value by the specified value with a specified scale before the operation.
*
* @param other the value to divide by
* @param beforeOperateScale the scale to be applied before the operation
* @return a {@code ChainedCalcUtil} instance with the updated value
*/
public ChainedCalcUtil divide(Number other, Integer beforeOperateScale) {
return operator(BigDecimal::divide, other, beforeOperateScale);
}
/**
* Divides the current value by the specified value with a specified scale.
*
* @param other the value to divide by
* @param scale the scale for the result
* @return a {@code ChainedCalcUtil} instance with the updated value
*/
public ChainedCalcUtil divideWithScale(Number other, Integer scale) {
return baseOperator(otherValue ->
this.value.divide(otherValue, scale, RoundingMode.HALF_UP), other, null);
}
/**
* Divides the current value by the specified value with a specified scale and a scale applied
* before the operation.
*
* @param other the value to divide by
* @param scale the scale for the result
* @param beforeOperateScale the scale to be applied before the operation
* @return a {@code ChainedCalcUtil} instance with the updated value
*/
public ChainedCalcUtil divideWithScale(Number other, Integer scale, Integer beforeOperateScale) {
return baseOperator((otherValue) ->
this.value.divide(otherValue, scale, RoundingMode.HALF_UP),
other, beforeOperateScale);
}
/**
* Returns the current value as a {@link BigDecimal} with the specified scale.
*
* @param scale the scale for the result
* @return the current value as a {@link BigDecimal} with the specified scale
*/
public BigDecimal getValue(int scale) {
return value.setScale(scale, RoundingMode.HALF_UP);
}
/**
* Returns the current value as a {@link BigDecimal}.
*
* @return the current value as a {@link BigDecimal}
*/
public BigDecimal getValue() {
return value;
}
/**
* Returns the current value as a {@link Double}.
*
* @return the current value as a {@link Double}
*/
public double getDouble() {
return getValue().doubleValue();
}
/**
* Returns the current value as a {@link Double} with the specified scale.
*
* @param scale the scale for the result
* @return the current value as a {@link Double} with the specified scale
*/
public double getDouble(int scale) {
return getValue(scale).doubleValue();
}
/**
* Returns the current value as a {@link Long}.
*
* @return the current value as a {@link Long}
*/
public long getLong() {
return getValue().longValue();
}
/**
* Returns the current value as an {@link Integer}.
*
* @return the current value as an {@link Integer}
*/
public int getInteger() {
return getValue().intValue();
}
/**
* Applies the specified operator function to the current value and another value.
*
* @param operator the operator function to apply
* @param otherValue the value to apply the operator with
* @return a ChainedCalcUtil instance with the updated value
*/
private ChainedCalcUtil operator(BiFunction<BigDecimal, BigDecimal, BigDecimal> operator, Object otherValue) {
return operator(operator, otherValue, 9);
}
/**
* Applies the specified operator function to the current value and another value with a
* specified scale before the operation.
*
* @param operator the operator function to apply
* @param other the value to apply the operator with
* @param beforeOperateScale the scale to be applied before the operation,
* or null if not applicable
* @return a ChainedCalcUtil instance with the updated value
*/
private ChainedCalcUtil operator(BiFunction<BigDecimal, BigDecimal, BigDecimal> operator,
Object other,
Integer beforeOperateScale) {
return baseOperator((otherValue) ->
operator.apply(this.value, otherValue),
other,
beforeOperateScale);
}
/**
* Applies the specified operator function to the current value and another
* value.
*
* @param operatorFunction the operator function to apply
* @param anotherValue the value to apply the operator with
* @param beforeOperateScale the scale to be applied before the operation,
* or null if not applicable
* @return a ChainedCalcUtil instance with the updated value
*/
private synchronized ChainedCalcUtil baseOperator(Function<BigDecimal, BigDecimal> operatorFunction,
Object anotherValue,
Integer beforeOperateScale) {
if (Objects.isNull(anotherValue)) {
return this;
}
if (anotherValue instanceof ChainedCalcUtil) {
this.value = operatorFunction.apply(((ChainedCalcUtil) anotherValue).getValue());
return this;
}
this.value = operatorFunction.apply(convertBigDecimal(anotherValue, beforeOperateScale));
return this;
}
/**
* Converts the specified value to a {@link BigDecimal}.
*
* @param value the value to convert
* @param scale the scale to apply to the resulting BigDecimal, or null if not applicable
* @return the converted BigDecimal value
*/
private BigDecimal convertBigDecimal(Object value, Integer scale) {
if (Objects.isNull(value)) {
return BigDecimal.ZERO;
}
BigDecimal res;
if (value instanceof Number num) {
res = BigDecimal.valueOf(num.doubleValue());
} else {
try {
res = new BigDecimal(value.toString());
} catch (NumberFormatException ignored) {
return BigDecimal.ZERO;
}
}
if (Objects.nonNull(scale)) {
return res.setScale(scale, RoundingMode.HALF_UP);
}
return res;
}
/**
* -- GETTER --
* Returns the current value as a BigDecimal.
*/
private BigDecimal value;
}
@@ -0,0 +1,117 @@
/*
* Copyright (C) 2024-2025 OnixByte.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.onixbyte.nums;
import com.onixbyte.nums.model.QuartileBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* A utility class that provides methods for calculating percentiles and interquartile range (IQR)
* bounds for a dataset.
* <p>
* This class contains static methods to:
* <ul>
* <li>Calculate a specified percentile from a list of double values using linear interpolation.</li>
* <li>Calculate interquartile bounds (Q1, Q3) and the corresponding lower and upper bounds,
* which can be used to identify outliers in the dataset.</li>
* </ul>
* <p>
* This class is final, meaning it cannot be subclassed, and it only contains static methods,
* so instances of the class cannot be created.
* <h2>Example usage:</h2>
* <pre>
* {@code
* List<Double> data = Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0);
* Double percentileValue = PercentileCalculator.calculatePercentile(data, 50.0); // Calculates median
* QuartileBounds bounds = PercentileCalculator.calculatePercentileBounds(data); // Calculates IQR bounds
* }
* </pre>
*
* @author zihluwang
* @version 1.6.5
* @since 1.6.5
*/
public final class PercentileCalculator {
private final static Logger log = LoggerFactory.getLogger(PercentileCalculator.class);
/**
* Private constructor to prevent instantiation of this utility class.
*/
private PercentileCalculator() {
}
/**
* Calculates the specified percentile from a list of values.
* <p>
* This method takes a list of double values and calculates the given percentile using linear
* interpolation between the two closest ranks. The list is first sorted in ascending order,
* and the specified percentile is then calculated.
*
* @param values a list of {@code Double} values from which the percentile is calculated.
* @param percentile a {@code Double} representing the percentile to be calculated (e.g., 50.0
* for the median)
* @return a {@code Double} value representing the calculated percentile
*/
public static Double calculatePercentile(List<Double> values, Double percentile) {
if (values.isEmpty()) {
throw new IllegalArgumentException("Unable to sort an empty list.");
}
var sorted = values.stream().sorted().toList();
var rank = percentile / 100. * (sorted.size() - 1);
var lowerIndex = (int) Math.floor(rank);
var upperIndex = (int) Math.ceil(rank);
var weight = rank - lowerIndex;
return sorted.get(lowerIndex) * (1 - weight) + sorted.get(upperIndex) * weight;
}
/**
* Calculates the interquartile range (IQR) and the corresponding lower and upper bounds
* based on the first (Q1) and third (Q3) quartiles of a dataset.
* <p>
* This method takes a list of double values, calculates the first quartile (Q1),
* the third quartile (Q3), and the interquartile range (IQR). Using the IQR, it computes
* the lower and upper bounds, which can be used to detect outliers in the dataset.
* The lower bound is defined as {@code Q1 - 1.5 * IQR}, and the upper bound is defined as
* {@code Q3 + 1.5 * IQR}.
*
* @param data a list of {@code Double} values for which the quartile bounds will be calculated
* @return a {@code QuartileBounds} object containing the calculated lower and upper bounds
*/
public static QuartileBounds calculatePercentileBounds(List<Double> data) {
var sorted = data.stream().sorted().toList();
var Q1 = calculatePercentile(sorted, 25.);
var Q3 = calculatePercentile(sorted, 75.);
var IQR = Q3 - Q1;
var lowerBound = Q1 - 1.5 * IQR;
var upperBound = Q3 + 1.5 * IQR;
return QuartileBounds.builder()
.upperBound(upperBound)
.lowerBound(lowerBound)
.build();
}
}
@@ -0,0 +1,127 @@
/*
* Copyright (C) 2024-2025 OnixByte.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.onixbyte.nums.model;
/**
* A record representing the quartile bounds of a dataset.
* <p>
* This class encapsulates the lower and upper bounds of a dataset, which are typically used for
* detecting outliers in the data. The bounds are calculated based on the interquartile range (IQR)
* of the dataset. Values below the lower bound or above the upper bound may be considered outliers.
* <p>
* Quartile bounds consist of:
* <ul>
* <li>{@code lowerBound} - The lower bound of the dataset, typically {@code Q1 - 1.5 * IQR}.</li>
* <li>{@code upperBound} - The upper bound of the dataset, typically {@code Q3 + 1.5 * IQR}.</li>
* </ul>
* <p>
* Example usage:
* <pre>
* QuartileBounds bounds = QuartileBounds.builder()
* .lowerBound(1.5)
* .upperBound(7.5)
* .build();
* </pre>
*
* @param upperBound the upper bound of the dataset
* @param lowerBound the lower bound of the dataset
* @author zihluwang
* @version 1.6.5
* @since 1.6.5
*/
public record QuartileBounds(
Double upperBound,
Double lowerBound
) {
/**
* Creates a new {@link Builder} instance for building a {@code QuartileBounds} object.
* <p>
* The {@link Builder} pattern is used to construct the {@code QuartileBounds} object with
* optional values for the upper and lower bounds.
* </p>
*
* @return a new instance of the {@link Builder} class
*/
public static Builder builder() {
return new Builder();
}
/**
* A builder class for constructing instances of the {@code QuartileBounds} record.
* <p>
* The {@link Builder} pattern allows for the step-by-step construction of a
* {@code QuartileBounds} object, providing a flexible way to set values for the lower and
* upper bounds. Once the builder has the required values, the {@link #build()} method creates
* and returns a new {@code QuartileBounds} object.
* </p>
* <p>
* Example usage:
* <pre>
* {@code
* QuartileBounds bounds = QuartileBounds.builder()
* .lowerBound(1.5)
* .upperBound(7.5)
* .build();
* }
* </pre>
*/
public static class Builder {
private Double upperBound;
private Double lowerBound;
/**
* Private constructor to prevent instantiation of this utility class.
*/
private Builder() {
}
/**
* Sets the upper bound for the {@code QuartileBounds}.
*
* @param upperBound the upper bound of the dataset
* @return the current {@code Builder} instance, for method chaining
*/
public Builder upperBound(Double upperBound) {
this.upperBound = upperBound;
return this;
}
/**
* Sets the lower bound for the {@code QuartileBounds}.
*
* @param lowerBound the lower bound of the dataset
* @return the current {@code Builder} instance, for method chaining
*/
public Builder lowerBound(Double lowerBound) {
this.lowerBound = lowerBound;
return this;
}
/**
* Builds and returns a new {@code QuartileBounds} instance with the specified upper and
* lower bounds.
*
* @return a new {@code QuartileBounds} object containing the specified bounds
*/
public QuartileBounds build() {
return new QuartileBounds(upperBound, lowerBound);
}
}
}
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (C) 2024-2024 OnixByte.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<configuration>
<property name="COLOURFUL_OUTPUT" value="%black(%date{'dd MMM, yyyy HH:mm:ss', Asia/Hong_Kong, en-UK}) %highlight(%-5level) %black(---) %black([%10.10t]) %cyan(%-20.20logger{20}) %black(:) %msg%n"/>
<property name="STANDARD_OUTPUT" value="%date{'dd MMM, yyyy HH:mm:ss', Asia/Hong_Kong, en-UK} %-5level %black(---) [%10.10t] %-20.20logger{20} : %msg%n"/>
<statusListener class="ch.qos.logback.core.status.NopStatusListener" />
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${COLOURFUL_OUTPUT}</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT"/>
</root>
</configuration>