ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
32.36k stars 2.36k forks source link

Unexpected type coercion comptime_int -> comptime_float #19574

Open jiacai2050 opened 3 months ago

jiacai2050 commented 3 months ago

Zig Version

0.12.0-dev.3533+e5d900268

Steps to Reproduce and Observed Behavior

pub fn main() !void {
    const v1 = 1 / 2 * 0.1;
    const v2 = 1.0 / 2.0 * 0.1;
    std.debug.print("v1:{any}, v2:{any}\n", .{ v1, v2 });
}

This will output

v1:0e0, v2:5e-2

This seems quite confusing.

    const f: f32 = 54.0 / 5;

Since this will throw error when compile according to docs here, I think v1 should also throw errors.

Expected Behavior

V1 should throw error when compile.

fifixc commented 3 months ago

In Zig, when you perform an operation between two integers and the result should be a floating point number, Zig first performs the operation between integers and then implicitly converts the result to a floating point if necessary.

In the expression 1/2 * 0.1, division 1/2 results in 0, which is an integer. However, when the 0 * 0.1 operation is performed, Zig implicitly converts the integer 0 to a floating point (0.0) so that multiplication can be performed between two floating point numbers, thus avoiding type errors.

Angluca commented 3 months ago

bug? const dd: f64 = @divxxx(1.0, 60.0f64) always 0, But 1.0 / 60.0 is ok. 96a1e984ebe6fe447afc9cff964a9b27

1087e585fe4011cdecc99e081ffdfb07