Last active
February 24, 2021 09:28
-
-
Save thinkphp/ae5024dbd0ea6b83b6308a028ea22323 to your computer and use it in GitHub Desktop.
Natural Logarithm in Golang.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Adrian Statescu <mergesortv@gmail.com | |
* Natural Logarithm in Golang. | |
* ln(1) = 0 | |
*/ | |
package main | |
import ("fmt" | |
"os" | |
"strconv" | |
"math") | |
func f(x, a float64) float64 { | |
return math.Exp(x) - a | |
} | |
func ln(n float64) float64 { | |
var lo, hi, m float64 | |
if n <= 0 { | |
return -1 | |
} | |
if n == 1 { | |
return 0 | |
} | |
EPS := 0.00001 | |
lo = 0 | |
hi = n | |
for math.Abs(lo - hi) >= EPS { | |
m = float64( (lo + hi) / 2.0 ) | |
if f(m, n) < 0 { | |
lo = m; | |
} else { | |
hi = m | |
} | |
} | |
return float64((lo+hi)/2.0) | |
} | |
func main() { | |
var n float64 | |
n,_ = strconv.ParseFloat(os.Args[1], 64) | |
fmt.Printf("ln(%f) = %.19f\n", n, ln(7)) | |
fmt.Printf("ln(%f) = %.19f", n, math.Log(7)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment