blob: 924ee7cc9735b8f2786643df84006295eee7bc92 [file] [log] [blame]
Ken Thompson21810982008-03-28 13:56:47 -07001// Copyright 2009 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
Rob Pike43312932008-06-27 17:06:23 -07005package math
Ken Thompson21810982008-03-28 13:56:47 -07006
Rob Pike1a13f9b2011-09-29 09:54:20 -07007// Abs returns the absolute value of x.
Charles L. Doriana0690b62010-02-01 22:21:40 -08008//
9// Special cases are:
Charles L. Dorianc8d25442011-11-28 13:04:52 -080010// Abs(±Inf) = +Inf
Rob Pike1a13f9b2011-09-29 09:54:20 -070011// Abs(NaN) = NaN
Brad Fitzpatrick6f8a6652015-10-29 15:13:58 +000012func Abs(x float64) float64 {
Brad Fitzpatricka59a2752015-10-29 13:02:28 -070013 // TODO: once golang.org/issue/13095 is fixed, change this to:
Brad Fitzpatrick6f8a6652015-10-29 15:13:58 +000014 // return Float64frombits(Float64bits(x) &^ (1 << 63))
15 // But for now, this generates better code and can also be inlined:
Brad Fitzpatricka59a2752015-10-29 13:02:28 -070016 if x < 0 {
Robert Griesemer40621d52009-11-09 12:07:39 -080017 return -x
Brad Fitzpatricka59a2752015-10-29 13:02:28 -070018 }
19 if x == 0 {
Rob Pike1a13f9b2011-09-29 09:54:20 -070020 return 0 // return correctly abs(-0)
Ken Thompson21810982008-03-28 13:56:47 -070021 }
Robert Griesemera3d10452009-12-15 15:35:38 -080022 return x
Ken Thompson21810982008-03-28 13:56:47 -070023}