javascript solves the default rounding pit (the best known solution)

Keywords: Javascript Java

Reproduce the problem

js always gets a more precise result when working with numbers, such as 1234/10 which is 123.4, but in c or java integer divided by 10 is still an integer and the decimal part is discarded, not only that*,% and so on, but sometimes we prefer to discard rounding

Use Math Standard Library

The Math Standard Library provides Math.floor(): Round down Math.ceil(): Round up Math.round(): Round around these three rounding methods, which are also very efficient, but when you do some operations, you always feel uncomfortable and inefficient. When you look at the source code of the Math section in v8, you find that a lot of operations are required to get results.


//All methods of the math library are declared in the builtins-math-gen.cc file
// ES6 #sec-math.floor
TF_BUILTIN(MathFloor, MathBuiltinsAssembler) {
  TNode<Context> context = CAST(Parameter(Descriptor::kContext));
  TNode<Object> x = CAST(Parameter(Descriptor::kX));
  MathRoundingOperation(context, x, &CodeStubAssembler::Float64Floor);
}
// floor operations were performed in the code-stub-assembler.cc file
TNode<Float64T> CodeStubAssembler::Float64Floor(SloppyTNode<Float64T> x) {
  if (IsFloat64RoundDownSupported()) {
    return Float64RoundDown(x);
  }
  TNode<Float64T> one = Float64Constant(1.0);
  TNode<Float64T> zero = Float64Constant(0.0);
  TNode<Float64T> two_52 = Float64Constant(4503599627370496.0E0);
  TNode<Float64T> minus_two_52 = Float64Constant(-4503599627370496.0E0);
  VARIABLE(var_x, MachineRepresentation::kFloat64, x);
  Label return_x(this), return_minus_x(this);
  // Check if {x} is greater than zero.
  Label if_xgreaterthanzero(this), if_xnotgreaterthanzero(this);
  Branch(Float64GreaterThan(x, zero), &if_xgreaterthanzero,
         &if_xnotgreaterthanzero);
  BIND(&if_xgreaterthanzero);
  {
    // Just return {x} unless it's in the range ]0,2^52[.
    GotoIf(Float64GreaterThanOrEqual(x, two_52), &return_x);
    // Round positive {x} towards -Infinity.
    var_x.Bind(Float64Sub(Float64Add(two_52, x), two_52));
    GotoIfNot(Float64GreaterThan(var_x.value(), x), &return_x);
    var_x.Bind(Float64Sub(var_x.value(), one));
    Goto(&return_x);
  }
  BIND(&if_xnotgreaterthanzero);
  {
    // Just return {x} unless it's in the range ]-2^52,0[
    GotoIf(Float64LessThanOrEqual(x, minus_two_52), &return_x);
    GotoIfNot(Float64LessThan(x, zero), &return_x);
    // Round negated {x} towards -Infinity and return the result negated.
    TNode<Float64T> minus_x = Float64Neg(x);
    var_x.Bind(Float64Sub(Float64Add(two_52, minus_x), two_52));
    GotoIfNot(Float64LessThan(var_x.value(), minus_x), &return_minus_x);
    var_x.Bind(Float64Add(var_x.value(), one));
    Goto(&return_minus_x);
  }
  BIND(&return_minus_x);
  var_x.Bind(Float64Neg(var_x.value()));
  Goto(&return_x);
  BIND(&return_x);
  return TNode<Float64T>::UncheckedCast(var_x.value());
}

Math.floor has many operations, high complexity, and many levels of recursion to get results

Using bitwise operators

In bitwise operators, ~is the bitwise inversion of numbers. Bit operations are faster operators in js. After two bitwise inversions of floating-point numbers, the result of rounding off is Math.floor(5.6)==~~5.6. This is the fastest known solution.
Sample Code


/**
 * @param {number} x
 * @return {number}
 */
var reverse = function (x) {
  let ans = 0;
  while (x !== 0) {
    ans = ans * 10 + ~~(x % 10);
    x = ~~(x / 10);
  }
  return (ans >= (2 ** 31) || ans <= -(2 ** 31)) ? 0 : ans;
};

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function (x) {
  let ans = 0;
  while (x !== 0) {
    ans = ans * 10 + Math.floor(x % 10);
    x = Math.floor(x / 10);
  }
  return (ans >= (2 ** 31) || ans <= -(2 ** 31)) ? 0 : ans;
};

The results from these two functions are exactly the same

Posted by phu on Sun, 17 Nov 2019 03:10:07 -0800