Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "strconv"
- "strings"
- )
- func Pow(base, degree int) int {
- result := 1
- for i := 0; i < degree; i++ {
- result *= base
- }
- return result
- }
- func Max(a, b int) int {
- if a > b {
- return a
- }
- return b
- }
- func computePreciselyMul(a, b float64) float64 {
- aStr := fmt.Sprintf("%f", a)
- bStr := fmt.Sprintf("%f", b)
- aParts := strings.Split(aStr, ".")
- bParts := strings.Split(bStr, ".")
- aFactor := 1
- bFactor := 1
- if len(aParts) >= 2 {
- aFactor = Pow(10, len(aParts[1]))
- }
- if len(bParts) >= 2 {
- bFactor = Pow(10, len(bParts[1]))
- }
- factor := aFactor * bFactor
- a *= float64(aFactor)
- b *= float64(bFactor)
- return a * b / float64(factor)
- }
- func computePreciselyDiff(a, b float64) float64 {
- aStr := strconv.FormatFloat(a, 'f', -1, 64)
- bStr := strconv.FormatFloat(b, 'f', -1, 64)
- aParts := strings.Split(aStr, ".")
- bParts := strings.Split(bStr, ".")
- aFactor := 1
- bFactor := 1
- if len(aParts) >= 2 {
- aFactor = Pow(10, len(aParts[1]))
- }
- if len(bParts) >= 2 {
- bFactor = Pow(10, len(bParts[1]))
- }
- factor := Max(aFactor, bFactor)
- a *= float64(factor)
- b *= float64(factor)
- return (a - b) / float64(factor)
- }
- func main() {
- a := 10.0
- b := 9.8
- c := a - b
- fmt.Println(c)
- rounded := computePreciselyDiff(a, b)
- fmt.Println(rounded)
- a = 0.2
- b = 0.05
- c = a - b
- fmt.Println(c)
- rounded = computePreciselyDiff(a, b)
- fmt.Println(rounded)
- a = 0.2
- b = 0.000005
- c = a - b
- fmt.Println(c)
- rounded = computePreciselyDiff(a, b)
- fmt.Println(rounded)
- a = 0.2
- b = 0.000000005
- c = a - b
- fmt.Println(c)
- rounded = computePreciselyDiff(a, b)
- fmt.Println(rounded)
- a = 2090.5
- b = 8.61
- c = a * b
- fmt.Println(c)
- rounded = computePreciselyMul(a, b)
- fmt.Println(rounded)
- fmt.Println(len("0.1999999999999993") - 2)
- fmt.Println(len("1000000000000") - 1)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement