gpt4 book ai didi

python - CVXPY 有办法将变量约束为偶数吗?

转载 作者:行者123 更新时间:2023-12-01 00:18:12 30 4
gpt4 key购买 nike

我正在尝试编写一个搜索时钟频率和除数的程序来生成目标频率。然而,一个限制是除数必须是偶数(由于硬件限制),我找不到一种方法来对此进行建模。

我没有得到模运算符支持

"TypeError: unsupported operand type(s) for %: 'Variable' and 'int'"

以下使用除法和乘法的黑客尝试不起作用:

wantipp = cp.Parameter(name = 'wantedipp')  # Desired IPP

div = cp.Variable(integer = True, name = 'div') # Divisor must be integral
ipp = cp.Variable(pos = True, name = 'ipp') # nsec
constraints = [
ipp == 1e9 / 6e6 * div, # Constrain IPP to divisor
div >= 2, div <= 65536, # Divisor must be 2-65536
div / 2 * 2 == div, # Divisor must be even (doesn't actually work)
]
objective = cp.Minimize(cp.abs(ipp - wantipp)) # Find closest possible IPP
prob = cp.Problem(objective, constraints);

for i in (1e3, 2e3, 1e6, 2e6, 123123, 5412341, 1233, 12541):
wantipp.value = i
prob.solve()
print('IPP %.3f nsec (%.3f Hz) -> Divisor %d %.3f nsec (%.3f Hz)' % (
i, 1e9 / i, div.value, ipp.value, 1e9 / ipp.value
))

IPP 1000.000 nsec (1000000.000 Hz) -> Divisor 6 1000.000 nsec (1000000.000 Hz)
IPP 2000.000 nsec (500000.000 Hz) -> Divisor 12 2000.000 nsec (500000.000 Hz)
IPP 1000000.000 nsec (1000.000 Hz) -> Divisor 6000 1000000.000 nsec (1000.000 Hz)
IPP 2000000.000 nsec (500.000 Hz) -> Divisor 12000 2000000.000 nsec (500.000 Hz)
IPP 123123.000 nsec (8121.959 Hz) -> Divisor 739 123166.667 nsec (8119.080 Hz)
IPP 5412341.000 nsec (184.763 Hz) -> Divisor 32474 5412333.333 nsec (184.763 Hz)
IPP 1233.000 nsec (811030.008 Hz) -> Divisor 7 1166.667 nsec (857142.857 Hz)
IPP 12541.000 nsec (79738.458 Hz) -> Divisor 75 12500.000 nsec (80000.000 Hz)

即它最终得到除数 739 等。

(请注意,我从固定时钟开始,稍后它会改变)

我在 MacOSX 10.14.6 上使用 CVXPY 1.0.25Python 3.7.5

最佳答案

创建约束为偶数的变量 x 的完全标准方法是添加整数变量 y 和约束 x=2y。

关于python - CVXPY 有办法将变量约束为偶数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59150061/

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