gpt4 book ai didi

javascript - 为什么使用processing.js从值中减去-0.2会将整数变成无理数?

转载 作者:行者123 更新时间:2023-12-03 06:06:53 25 4
gpt4 key购买 nike

我正在循环遍历一个随着时间推移而衰减的对象的 if 语句,每次获取该值并减去 -0.2。第一次通过后,数字会变得很奇怪,比如 0.9653677422,而不是保持 0.2 的倍数(4.2、4.0、3.8、3.6...等)

初始值为7

示例:

if (this.health > 0){
this.health = this.health - 0.2;
}else{
return;
}

为什么使用processing.js从值中减去-0.2会将整数变成无理数?

编辑***通过adonike's answer我了解到使用浮点二进制点数无法 100% 准确地表示小数。通过将所有数字保持为整数(将初始值乘以 10 并减去要减去的值),可以保留相同的衰减率(每个循环 1/35)而不会损失精度。初始值的数字变为 70,衰减率(减去数字)变为 2,一切顺利。

也可以将初始值设为 35,将减去的数字设为 1,并获得相同的所需结果。

有关此内容的更多见解,请参阅:Why can't decimal numbers be represented exactly in binary?以及 Kevin Workman's 中提供的链接answer .

该问题派生的代码如下所示:

var Tile = function(x, y, sourceImg) {
this.x = x;
this.y = y;
this.width = 25;
this.health = 35;
this.healthMax = this.health;
this.decayRate = 1;
this.daysOld = 0;
};

Tile.prototype.drawPlantTiles = function() {
if (this.health > this.healthMax/2){
this.occupied = true;
fill(168, 118, 25);
stroke(163, 109, 21);
rect(this.x, this.y, this.width, this.width,0);
strokeWeight(1);
noStroke();
image(plantImg1, this.x, this.y, this.width, this.width);
this.health = this.health - this.decayRate;
this.daysOld++;
} else if (this.health > this.healthMax/4 && this.health <= this.healthMax/2){
this.occupied = true;
fill(168, 118, 25);
stroke(163, 109, 21);
rect(this.x, this.y, this.width, this.width,0);
strokeWeight(1);
noStroke();
image(plantImg2, this.x, this.y, this.width, this.width);
this.health = this.health - this.decayRate;
this.daysOld++;
} else if (this.health > 0 && this.health <= this.healthMax/4){
this.occupied = true;
fill(168, 118, 25);
stroke(163, 109, 21);
rect(this.x, this.y, this.width, this.width,0);
strokeWeight(1);
noStroke();
image(plantImg3, this.x, this.y, this.width, this.width);
this.health = this.health - this.decayRate;
this.daysOld++;
}else{
fill(168, 118, 25);
stroke(163, 109, 21);
rect(this.x, this.y, this.width, this.width,0);
strokeWeight(1);
noStroke();
this.state = false;
return;
}
};

注意:“this.healthMax”阈值仍需要重新设计,以删除所有小数/保持 100% 的精度。

最佳答案

另一个答案是正确的,但我想提供更多细节。

这是解决此问题的首选文章:What Every Computer Scientist Should Know About Floating-Point Arithmetic

这是一个较短的、特定于 JavaScript 的版本:What Every JavaScript Developer Should Know About Floating Points

本文列出了一些解决该问题的库:

另请参阅:

关于javascript - 为什么使用processing.js从值中减去-0.2会将整数变成无理数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39503299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com