blob: 361a6c1e62e249745ccb13174b00d68b214bf6fb [file] [log] [blame]
Marcel van Lohuizen7b5d2fd2018-12-11 16:34:56 +01001// Copyright 2018 The CUE Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package math
16
Marcel van Lohuizenb05c7682019-07-25 17:51:24 +020017import (
18 "math"
19
20 "cuelang.org/go/internal"
21 "github.com/cockroachdb/apd/v2"
22)
Marcel van Lohuizen7b5d2fd2018-12-11 16:34:56 +010023
24// TODO: use apd
25
26// Floor returns the greatest integer value less than or equal to x.
27//
28// Special cases are:
29// Floor(±0) = ±0
30// Floor(±Inf) = ±Inf
31// Floor(NaN) = NaN
32func Floor(x float64) float64 {
33 return math.Floor(x)
34}
35
36// Ceil returns the least integer value greater than or equal to x.
37//
38// Special cases are:
39// Ceil(±0) = ±0
40// Ceil(±Inf) = ±Inf
41// Ceil(NaN) = NaN
42func Ceil(x float64) float64 {
43 return math.Ceil(x)
44}
45
46// Trunc returns the integer value of x.
47//
48// Special cases are:
49// Trunc(±0) = ±0
50// Trunc(±Inf) = ±Inf
51// Trunc(NaN) = NaN
52func Trunc(x float64) float64 {
53 return math.Trunc(x)
54}
55
56// Round returns the nearest integer, rounding half away from zero.
57//
58// Special cases are:
59// Round(±0) = ±0
60// Round(±Inf) = ±Inf
61// Round(NaN) = NaN
62func Round(x float64) float64 {
63 return math.Round(x)
64}
65
66// RoundToEven returns the nearest integer, rounding ties to even.
67//
68// Special cases are:
69// RoundToEven(±0) = ±0
70// RoundToEven(±Inf) = ±Inf
71// RoundToEven(NaN) = NaN
72func RoundToEven(x float64) float64 {
73 return math.RoundToEven(x)
74}
Marcel van Lohuizenb05c7682019-07-25 17:51:24 +020075
76var mulContext = apd.BaseContext.WithPrecision(1)
77
78// MultipleOf reports whether x is a multiple of y.
79func MultipleOf(x, y *internal.Decimal) (bool, error) {
80 var d apd.Decimal
81 cond, err := mulContext.Quo(&d, x, y)
82 return !cond.Inexact(), err
83}