我需要平衡三个变量,以便在向其中一个添加值时,其他变量按比例变化,从而使金额保持原始状态。 例如,辐射4中的身体三角形。https://i.imgur.com/Q2cv9Xm.jpg
我尝试了一些方法,但这是不正确的,实际上是行不通的。
首先,我只是将缺失的数量添加到其他变量中,但是没有比例关系。
第二,我试图按比例进行平衡:
public class Triangle()
{
float a = 0.33f;
float b = 0.33f;
float c = 0.33f;
static float sum = 0.99f;
static float maxVal = 0.97f;
void AddA(float value) {
if (a + value <= maxVal) {
a += value;
float ratio1 = b/sum;
float ratio2 = c/sum;
// difference between needed sum and current
float remainderSum = a+b+c-sum;
// the excess part is proportional to b
float rem1 = remainderSum*ratio1;
// the excess part is proportional to c
float rem2 = remainderSum*ratio2;
// subtract excess
b -= rem1;
c -= rem2;
}
}
}
结果:
Add(0.5f); =>
Sum: 1.1566666666666665
ABC: 0.8300000000000001/0.16333333333333325/0.16333333333333325
但结果总和不正确。
答案 0 :(得分:1)
每次将一个变量增加一个,就想减少另外两个变量。如果将它们各减小一半,则所有三个变量的总和保持不变。
伪代码:
total = 1; //you could change this to anything
x = total/3;
y = total/3;
z = total/3;
def increaseX(amount) {
x = x + amount;
y = y - amount/2;
z = z - amount/2;
}
def increaseY(amount) {
y = y + amount;
x = x - amount/2;
z = z - amount/2;
}
def increaseZ(amount) {
z = z + amount;
x = x - amount/2;
y = y - amount/2;
}
答案 1 :(得分:-1)
class Param3:
MAX = 300
a = 100
b = 100
c = 100
def __init__(self, a, b):
self.a = a
self.b = b
self.c = MAX-a-b
def add_A(val):
# Limitation
if a+val > MAX:
val = MAX-a
print("A > MAX, must be <=")
elif a+val < 0:
val = -a
print("A < 0, must be >=")
a += val
var coef = b/(b+c)
b -= val*coef
c = MAX - a - b