Please tell me the reason why the calculation results don't match.

Asked 2 years ago, Updated 2 years ago, 48 views

If you calculate 100000000000000000000×100000000000000000000 in the Go language, the result is
Now -5527149226598858752.
Simply put, I think it would be 100000000000000000000000000000000000000000000.

By the way, the code I executed is as follows:

package main
import "fmt"

funcmain(){

    i —=100000000000000000000000000
    fmt.Println(i*i)

}

If I do the same thing with Ruby, it will be 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

i=1000000000000000000000000
pi*i

ruby go

2022-09-29 22:13

2 Answers

int is a signed 32/64-bit integer, so you can't handle very large values.

  • int32:-2147483648 to 2147483647
  • int64:-9223372036854775808 to 9223372036854775807 (int in 64-bit environment)

Use the "math/big" package when dealing with a larger range of numbers.

package main
import "fmt"
import "math/big"

funcmain(){
  biNum: = big.NewInt (100000000000000000000)
  result: = new(big.Int)
  result.Mul(biNum,biNum)
  fmt.Printf("%v*%v=%v\n", biNum, biNum, result)
}

Output (Online)

1000000000000000000*10000000000000000=100000000000000000000000000000000000000000000

For Ruby, on the other hand, if you look at the following, you can see that it was used differently for large numerical objects in areas that were not visible from the coder.

p1.0.class
= > Float
p 1000000000000000000.class
=>Fixnum
p 10000000000000000000.class
=>Bignum

a = 1000000000000000000000000
b = 1000000000000000000000
c=a*b

pa.class
=>Fixnum
pb.class
=>Bignum
pc.class
=>Bignum


2022-09-29 22:13

This is because the calculation results exceed the integer range that can be handled by the int32 type or int64 type variable.
We recommend using the big.Int package big-The Go Programming Language.

package main

import(
    "fmt"
    "math/big"
)

funcmain(){
    i: = big.NewInt (1000000000000000000)
    fmt.Println(i.Mul(i,i))

    // Maximum values for int64 and uint64
    fmt.Printf("MaxInt64=%20d\n", int64(math.MaxInt64))
    fmt.Printf("MaxUint64=%20d\n", uint64(math.MaxUint64))
}

In addition, math/const.go defines the maximum and minimum values for each integer type.

// Integer limit values.
const(
    MaxInt8 = 1<7-1
    MinInt8=-1<<7
    MaxInt16 = 1<<15-1
    MinInt16=-1<<15
    MaxInt32 = 1<<31-1
    MinInt32 = -1<<31
    MaxInt64 = 1<<63-1
    MinInt64 = -1<<63
    MaxUint8 = 1<<8-1
    MaxUint16 = 1<<16-1
    MaxUint32 = 1<<32-1
    MaxUint64 = 1<64-1
)

Note that these constants are not declared of type.Therefore, type conversion may be required for use.

fmt.Println (math.MaxUint64)
=>constant18446744073709551615 overflow int
fmt.Println(uint64(math.MaxUint64))
=>18446744073709551615


2022-09-29 22:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.