Data Types: Float and Float32
● Beginner3 min
Float is a number with a fraction, in 64 bits; Float32 is the 32-bit kind that GPUs compute fastest.
fn main() {
const pi = 3.14159
const half: Float32 = 0.5
print(pi)
print(half)
print(7.0 / 2.0)
print(1e9)
}The program ran and printed:
kavach run float.kav
3.141590.53.51000000000.0
A Float always prints with a point or an exponent (1000000000.0), so you can tell it from an Int. Floats are stored in binary, so most decimals are kept a tiny bit off; for money, use Decimal.
Its 64 bits
Binary formats store a Float as its 64 bits in IEEE 754 form. x.bits() gives them as a UInt64, and Float.from_bits(n) turns them back into the same Float:
fn main() {
const x = 1.5
const bits = x.bits()
print(bits)
print(Float.from_bits(bits))
print(Float.from_bits(bits).bits() == bits)
}The program ran and printed:
kavach run float-bits.kav
46094342186137026561.5true