在没有条件比较的情况下以数学方式找到最大值 [英] Mathematically Find Max Value without Conditional Comparison

查看:112
本文介绍了在没有条件比较的情况下以数学方式找到最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

----------更新了------------

到目前为止,codymanix和Moonshadow一直是一个很大的帮助.我能够使用方程式解决问题,而无需使用右移,而是除以29.因为32位有符号2 ^ 31 =溢出到29.有效!

PHP原型

$r = $x - (($x - $y) & (($x - $y) / (29)));

LEADS的实际代码(每行只能执行一个数学函数!!!! AHHHH !!!)

DERIVDE1 = IMAGE1 - IMAGE2;
DERIVED2 = DERIVED1 / 29;
DERIVED3 = DERIVED1 AND DERIVED2;
MAX = IMAGE1 - DERIVED3;

----------原始问题-----------
我认为应用程序的局限性不可能实现,但我认为值得一试.

我将尝试简化这一过程.我需要找到两个数字之间的最大值,而不能使用IF或任何条件语句.

为了找到MAX值,我只能执行以下功能

Divide, Multiply, Subtract, Add, NOT, AND ,OR

假设我有两个数字

A = 60;
B = 50;

现在,如果A始终大于B,则找到最大值很简单

MAX = (A - B) + B;
ex. 
10 = (60 - 50)
10 + 50 = 60 = MAX

问题是A并不总是大于B.我无法使用我正在使用的脚本应用程序执行ABS,MAX,MIN或条件检查.

使用上面的受限操作是否有可能找到非常接近最大值的值?

解决方案

找到最多2个变量:

max = a-((a-b)&((a-b)>>31))

其中>>是按位右移(也称为SHR或ASR依赖于签名).

您使用的位数是31,而不是31.

----------Updated ------------

codymanix and moonshadow have been a big help thus far. I was able to solve my problem using the equations and instead of using right shift I divided by 29. Because with 32bits signed 2^31 = overflows to 29. Which works!

Prototype in PHP

$r = $x - (($x - $y) & (($x - $y) / (29)));

Actual code for LEADS (you can only do one math function PER LINE!!! AHHHH!!!)

DERIVDE1 = IMAGE1 - IMAGE2;
DERIVED2 = DERIVED1 / 29;
DERIVED3 = DERIVED1 AND DERIVED2;
MAX = IMAGE1 - DERIVED3;

----------Original Question-----------
I don't think this is quite possible with my application's limitations but I figured it's worth a shot to ask.

I'll try to make this simple. I need to find the max values between two numbers without being able to use a IF or any conditional statement.

In order to find the the MAX values I can only perform the following functions

Divide, Multiply, Subtract, Add, NOT, AND ,OR

Let's say I have two numbers

A = 60;
B = 50;

Now if A is always greater than B it would be simple to find the max value

MAX = (A - B) + B;
ex. 
10 = (60 - 50)
10 + 50 = 60 = MAX

Problem is A is not always greater than B. I cannot perform ABS, MAX, MIN or conditional checks with the scripting applicaiton I am using.

Is there any way possible using the limited operation above to find a value VERY close to the max?

解决方案

finding the maximum of 2 variables:

max = a-((a-b)&((a-b)>>31))

where >> is bitwise right-shift (also called SHR or ASR depeding on signedness).

Instead of 31 you use the number of bits your numbers have minus one.

这篇关于在没有条件比较的情况下以数学方式找到最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆