我在R中创建了一个while循环,它找到了在生产率/ ha不大于最大生产率的条件下生成集合总生产(prodTarget)所需的给定区域的最小比例。
while循环本身工作正常并完全按照它应该做的,问题发生在循环之后,我从最小比例(由while循环给出)创建一个序列到1。 while循环找到的最小比例为1,seq()命令返回错误(下面代码中的第一个版本)。但是,seq(1,1,0.1)手动正常工作并按预期返回1.
conservation_Yield<-8.4 # set minimal Yield/ha
max_current_Yield<-173.1 # the maximum observed Yield/ha
Area <- 226.02 # the area in ha
min_target <- conservation_Yield*Area
max_target <- max_current_Yield*Area
prodTargets <- seq(min_target,max_target,Area) # set a range of production targets
# Start loop over all production targets (166 in total, the last two loops are the problem)
for (i in 165: length(prodTargets)){
currentTarget <- prodTargets[i]
# Define the range of proportion managed land from the minimum feasable (given the target and maximum productivity)
# to maximum possible
min_proportion <- 0 # to find the minimum feasable, we set the proportion to zero
control_Yield <- max_current_Yield*10 # set to arbitrary higher value as max possible yield
while (control_Yield > max_current_Yield){
min_proportion <- min_proportion+0.01 # increase the proportion of managed land
rest_productivity <- currentTarget-conservation_Yield*Area*(1-min_proportion)
control_Yield <- rest_productivity/(Area*min_proportion)
}
max_proportion <- 1 # the maximum possible proportion is always 1
# First version: works fine for all loops except where min_proportion has to be 1 as well
landsparing_scenarios <- seq(min_proportion,max_proportion,0.01) # returns an error
# Second version: Check if min_proportion == 1 and create a vector of 1 manually
if (min_proportion == 1) { # returns FALSE even though min_proportion is 1
landsparing_scenarios <- 1
} else {
landsparing_scenarios <- seq(min_proportion,max_proportion,0.01)
}
# Third version: Check if min_proportion > 0.99 and create a vector of 1 manually
if (min_proportion > 0.99) {
landsparing_scenarios <- 1
} else {
landsparing_scenarios <- seq(min_proportion,max_proportion,0.01)
}
}
我添加了一个if-else子句来检查最小比例是否等于1(第二个版本)。现在,即使min_proportion在控制台中键入时返回数字1,命令min_proportion == 1也会返回FALSE。 变量怎么可能看起来是1而逻辑运算符不一致?
答案 0 :(得分:0)
在while循环期间,每次迭代时将0.01的值添加到最小比例。虽然min_proportion的输出表明循环的最后一步是min_proportion = 0.99+0.01
,但结果数在第16位时大于1。
尝试使用seq(min_proportion,1,0.01)
创建序列会导致错误,因为min_proportion实际上是1.000000000000001,大于1,因此这个序列是不可能的。这也是测试min_proportion == 1
返回FALSE
,但测试min_proportion > 0.99
返回TRUE
的原因。
一种可能的解决方案是在while循环后将变量min_proportion舍入为2位数。另一种可能性(正如@lmo所指出的)是使用不如all.equal(min_proportion, 1)
严格的函数==
。