Home > Mobile >  Golang - Small fractional numbers: How to divide 1 by a massive number
Golang - Small fractional numbers: How to divide 1 by a massive number

Time:07-11

I was wondering what would be the best way to produce a really small number in go?

I.e. doing the division for 1/x where x is a number > 1*10^70

I'm trying:

    target := "00000067c5b90000000000000000000000000000000000000000000000000000"
    targetValue := new(big.Int)
    targetValue.SetString(target, 16)
    
    one := new(big.Int)
    one.newInt(1)
    
    fmt.Println(new(big.Float).Quo(one, target)) // Fails because it needs floats input

CodePudding user response:

You seem most of the way there, you only needed to read the documentation.

package main

import (
    "fmt"
    "math/big"
)

func main() {
    target := "00000067c5b90000000000000000000000000000000000000000000000000000"
    targetValue := new(big.Int)
    targetValue.SetString(target, 16)
    targetFloat := big.NewFloat(1)
    targetFloat.SetInt(targetValue)
    fmt.Printf("%g\n", targetFloat)
    one := big.NewFloat(1)
    fmt.Printf("%g\n", new(big.Float).Quo(one, targetFloat))
}

Playground: https://go.dev/play/p/ci9mQWn6h-h

A value such as 10^70 fits into float64.

  •  Tags:  
  • go
  • Related