Skip to content

Commit

Permalink
fix: Division of integers gives truncated value
Browse files Browse the repository at this point in the history
  • Loading branch information
giann committed Sep 9, 2023
1 parent f4ff372 commit f4acc95
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 12 deletions.
2 changes: 1 addition & 1 deletion src/node.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2574,7 +2574,7 @@ pub const BinaryNode = struct {
return Value.fromFloat((right_f orelse @as(f64, @floatFromInt(right_i.?))) / (left_f orelse @as(f64, @floatFromInt(left_i.?))));
}

return Value.fromFloat(@as(f64, @floatFromInt(right_i.?)) / @as(f64, @floatFromInt(left_i.?)));
return Value.fromInteger(@divTrunc(right_i.?, left_i.?));
},
.Percent => {
if (right_f != null or left_f != null) {
Expand Down
7 changes: 1 addition & 6 deletions src/parser.zig
Original file line number Diff line number Diff line change
Expand Up @@ -4337,6 +4337,7 @@ pub const Parser = struct {
.Minus,
.Star,
.Percent,
.Slash,
=> try self.gc.type_registry.getTypeDef(
ObjTypeDef{
.def_type = if ((left.type_def != null and left.type_def.?.def_type == .Float) or (right.type_def != null and right.type_def.?.def_type == .Float))
Expand All @@ -4346,12 +4347,6 @@ pub const Parser = struct {
},
),

.Slash => try self.gc.type_registry.getTypeDef(
ObjTypeDef{
.def_type = .Float,
},
),

else => unreachable,
};

Expand Down
14 changes: 11 additions & 3 deletions src/vm.zig
Original file line number Diff line number Diff line change
Expand Up @@ -3033,9 +3033,17 @@ pub const VM = struct {
const right_i: ?i32 = if (right.isInteger()) right.integer() else null;
const left_i: ?i32 = if (left.isInteger()) left.integer() else null;

self.push(
Value.fromFloat((left_f orelse @as(f64, @floatFromInt(left_i.?))) / (right_f orelse @as(f64, @floatFromInt(right_i.?)))),
);
if (left_f != null or right_f != null) {
self.push(
Value.fromFloat(
(left_f orelse @as(f64, @floatFromInt(left_i.?))) / (right_f orelse @as(f64, @floatFromInt(right_i.?))),
),
);
} else {
self.push(
Value.fromInteger(@divTrunc(left_i.?, right_i.?)),
);
}

const next_full_instruction: u32 = self.readInstruction();
@call(
Expand Down
4 changes: 2 additions & 2 deletions tests/028-math.buzz
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ test "math" {
assert(math.sqrt(12.234) == 3.4977135388707863, message: "math.sqrt");
assert(math.tan(12.234) == -0.34517576763481983, message: "math.tan");

assert(math.min(a: 12.0, b: 124.0) == 12, message: "math.min");
assert(math.max(a: 12.0, b: 124.0) == 124, message: "math.max");
assert(math.minInt(a: 12, b: 124) == 12, message: "math.min");
assert(math.maxInt(a: 12, b: 124) == 124, message: "math.max");

float r = math.random();
assert(r >= 0 and r <= 1, message: "math.random");
Expand Down

0 comments on commit f4acc95

Please sign in to comment.