github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/testdata/float.go (about)

     1  package main
     2  
     3  func main() {
     4  	// sanity
     5  	println(3.14159265358979323846)
     6  
     7  	// float64
     8  	f64 := float64(2) / float64(3)
     9  	println(f64)
    10  	println(f64 + 1.0)
    11  	println(f64 - 1.0)
    12  	println(f64 * 2.0)
    13  	println(f64 / 2.0)
    14  
    15  	// float32
    16  	f32 := float32(2) / float32(3)
    17  	println(f32)
    18  	println(f32 + 1.0)
    19  	println(f32 - 1.0)
    20  	println(f32 * 2.0)
    21  	println(f32 / 2.0)
    22  
    23  	// casting
    24  	println(float32(f64))
    25  	println(float64(f32))
    26  
    27  	// float -> int
    28  	var f1 float32 = 3.3
    29  	var f2 float32 = 5.7
    30  	var f3 float32 = -2.3
    31  	var f4 float32 = -11.8
    32  	println(int32(f1), int32(f2), int32(f3), int32(f4))
    33  
    34  	// float -> int saturating behavior
    35  	var f5 float32 = -1
    36  	var f6 float32 = 256
    37  	var f7 float32 = -129
    38  	f8 := float32(^uint32(0))
    39  	f9 := float32(int32(-2147483648))
    40  	f10 := float32(int32(2147483647))
    41  	var inf float32 = 1
    42  	inf /= 0
    43  	var nan float32 = 0
    44  	nan /= 0
    45  	println(uint8(f5), uint8(f6), int8(f7), int8(f6), uint32(f8), int32(f9), int32(f10),
    46  		uint8(inf), uint8(-inf), int8(inf), int8(-inf), uint8(nan), int64(nan))
    47  
    48  	// int -> float
    49  	var i1 int32 = 53
    50  	var i2 int32 = -8
    51  	var i3 uint32 = 20
    52  	println(float32(i1), float32(i2), float32(i3))
    53  
    54  	// complex64
    55  	c64 := complex(f32, 1.2)
    56  	println(c64)
    57  	println(real(c64))
    58  	println(imag(c64))
    59  
    60  	// complex128
    61  	c128 := complex(f64, -2.0)
    62  	println(c128)
    63  	println(real(c128))
    64  	println(imag(c128))
    65  
    66  	// untyped complex
    67  	println(2 + 1i)
    68  	println(complex(2, -2))
    69  
    70  	// cast complex
    71  	println(complex64(c128))
    72  	println(complex128(c64))
    73  
    74  	// binops and negate on complex numbers
    75  	c64 = 5 + 2i
    76  	println("complex64 add: ", c64+-3+8i)
    77  	println("complex64 sub: ", c64 - -3 + 8i)
    78  	println("complex64 mul: ", c64*-3+8i)
    79  	println("complex64 div: ", c64/-3+8i)
    80  	println("complex64 neg: ", -c64)
    81  	c128 = -5 + 2i
    82  	println("complex128 add:", c128+2+6i)
    83  	println("complex128 sub:", c128-2+6i)
    84  	println("complex128 mul:", c128*2+6i)
    85  	println("complex128 div:", c128/2+6i)
    86  	println("complex128 neg:", -c128)
    87  }