Skip to content

Instantly share code, notes, and snippets.

@maxymania
Last active November 4, 2018 13:27
Show Gist options
  • Save maxymania/ca807dfc8871200a744833583943833b to your computer and use it in GitHub Desktop.
Save maxymania/ca807dfc8871200a744833583943833b to your computer and use it in GitHub Desktop.
Logarithm of 2 (Algorithm)
package main
import "fmt"
import "math"
func log2(f float64) (float64) {
frac, exp := math.Frexp(f)
exp--
frac*=2
log := float64(0)
part := float64(1)
for i := 0 ; i<32; i++ {
/* frac >= 2.0 */
if frac>1.999999999999 {
log += part
frac /= 2
}
frac *= frac
part /= 2
}
return float64(exp)+log
}
func main(){
for i := 0; i<11; i++ {
f := float64(i)/10.0
e := math.Exp2(f)
fmt.Printf("%f\t%f\t%f\n",f,math.Log2(e),log2(e))
}
}
package main
import "fmt"
import "math"
import "math/bits"
func log2(f float64) (float64) {
frac, exp := math.Frexp(f)
exp--
frac*=2
log := float64(0)
part := float64(1)
for i := 0 ; i<32 ; i++ {
/* frac >= 2.0 */
if frac>1.999999999999 {
log += part
frac /= 2
}
frac *= frac
part /= 2
}
return float64(exp)+log
}
func main2(){
for i := 0; i<11; i++ {
f := float64(i)/10.0
e := math.Exp2(f)
fmt.Printf("%f\t%f\t%f\n",f,math.Log2(e),log2(e))
}
}
func lshift(i uint64,s int) uint64 {
if s<0 { return i >> uint(-s) }
return i << uint(s)
}
func ilog2(i int) (float64) {
const TWO = 1<<31
exp := bits.Len(uint(i))
exp--
frac := lshift(uint64(i),30-exp)
log := float64(exp)
part := float64(1)
for i := 0 ; i<30 ; i++ {
if frac>=TWO {
frac >>= 1
log += part
} else {
}
part /= 2
frac = (frac*frac)>>30
}
return log
}
func ilog2n(i,n int) (int) {
const TWO = 1<<31
exp := bits.Len(uint(i))
exp--
frac := lshift(uint64(i),30-exp)
log := exp*n
part := n
for i := 0 ; i<30 ; i++ {
if frac>=TWO {
frac >>= 1
log += part
} else {
}
part /= 2
frac = (frac*frac)>>30
}
return log
}
func main(){
for i := 1; i<10; i++ {
f := float64(i)
//fmt.Printf("%f\t%f\t%f\n",f,math.Log2(f),ilog2(i))
fmt.Printf("%f\t%f\t%d\n",math.Log2(f),ilog2(i),ilog2n(i,100)/33)
//fmt.Printf("%f\t%f\t%f\t%f\n",f,math.Log2(f),log2(f),ilog2(i))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment