1
0
mirror of https://github.com/golang/go synced 2024-10-05 05:11:25 -06:00
go/src/lib/math/pow.go

62 lines
941 B
Go
Raw Normal View History

2008-03-28 14:56:47 -06:00
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package math
2008-03-28 14:56:47 -06:00
import "math"
2008-03-28 14:56:47 -06:00
/*
arg1 ^ arg2 (exponentiation)
*/
export func Pow(arg1,arg2 float64) float64 {
2008-03-28 14:56:47 -06:00
if arg2 < 0 {
return 1/Pow(arg1, -arg2);
2008-03-28 14:56:47 -06:00
}
if arg1 <= 0 {
if(arg1 == 0) {
if arg2 <= 0 {
2008-07-07 15:07:46 -06:00
return sys.NaN();
2008-03-28 14:56:47 -06:00
}
return 0;
}
temp := Floor(arg2);
2008-03-28 14:56:47 -06:00
if temp != arg2 {
2008-09-01 15:37:32 -06:00
panic(sys.NaN());
2008-03-28 14:56:47 -06:00
}
l := int32(temp);
2008-03-28 14:56:47 -06:00
if l&1 != 0 {
return -Pow(-arg1, arg2);
2008-03-28 14:56:47 -06:00
}
return Pow(-arg1, arg2);
2008-03-28 14:56:47 -06:00
}
temp := Floor(arg2);
2008-03-28 14:56:47 -06:00
if temp != arg2 {
if arg2-temp == .5 {
if temp == 0 {
return Sqrt(arg1);
2008-03-28 14:56:47 -06:00
}
return Pow(arg1, temp) * Sqrt(arg1);
2008-03-28 14:56:47 -06:00
}
return Exp(arg2 * Log(arg1));
2008-03-28 14:56:47 -06:00
}
l := int32(temp);
2008-03-28 14:56:47 -06:00
temp = 1;
for {
if l&1 != 0 {
temp = temp*arg1;
}
2008-07-08 21:48:41 -06:00
l >>= 1;
2008-03-28 14:56:47 -06:00
if l == 0 {
return temp;
}
2008-07-08 21:48:41 -06:00
arg1 *= arg1;
2008-03-28 14:56:47 -06:00
}
panic("unreachable")
2008-03-28 14:56:47 -06:00
}