1 /*******************************************************************************
2 * Copyright (c) 2016 Ericsson
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
8 *******************************************************************************/
10 package org
.eclipse
.tracecompass
.common
.core
.math
;
13 * Saturated arithmetic. These are mathematical helper functions that are used
14 * to clamp numbers to maximum and mimumum and avoid overflows.
16 * @author Matthew Khouzam
19 public final class SaturatedArithmetic
{
21 private SaturatedArithmetic() {
26 * Saturated multiplication. It will not overflow but instead clamp the
27 * result to {@link Long#MAX_VALUE} and {@link Long#MIN_VALUE}.
30 * The left long to multiply
32 * The right long to multiply
33 * @return The saturated multiplication result. The mathematical, not Java
34 * version of Min(Max(MIN_VALUE, left*right), MAX_VALUE).
35 * @see <a href="http://en.wikipedia.org/wiki/Saturation_arithmetic">
36 * Saturation arithmetic</a>
38 public static long multiply(long left
, long right
) {
39 long retVal
= left
* right
;
40 if ((left
!= 0) && ((retVal
/ left
) != right
)) {
41 return (sameSign(left
, right
) ? Long
.MAX_VALUE
: Long
.MIN_VALUE
);
47 * Saturated addition. It will not overflow but instead clamp the result to
48 * {@link Long#MAX_VALUE} and {@link Long#MIN_VALUE}.
51 * The left long to add
53 * The right long to add
54 * @return The saturated addition result. The mathematical, not Java version
55 * of Min(Max(MIN_VALUE, left+right), MAX_VALUE).
56 * @see <a href="http://en.wikipedia.org/wiki/Saturation_arithmetic">
57 * Saturation arithmetic</a>
60 public static final long add(final long left
, final long right
) {
61 long retVal
= left
+ right
;
62 if (sameSign(left
, right
) && !sameSign(left
, retVal
)) {
63 if (retVal
> 0 || left
== Long
.MIN_VALUE
) {
64 return Long
.MIN_VALUE
;
66 return Long
.MAX_VALUE
;
72 * Test if two numbers are the same sign or not
78 * @return true if both left and right are positive or both negative, false
81 public static boolean sameSign(final long left
, final long right
) {
82 return (left ^ right
) >= 0;
This page took 0.041466 seconds and 6 git commands to generate.