之前突然想起以前不记得在哪看见过的一种不需要比较的最大最小值函数的定义,觉得很有意思所以记录一下。
原理
这种最大最小值的本质上是计算出来的,需要定义加减法标量除法还有绝对值。
先来看看min(a,b)的计算1
min(a,b)=(a+b-|a-b|)/2
这样看可能不清楚,画个图
数学证明的话,
当a=b时,有|a-b|=0
成立
当a>b时,有|a-b|=a-b
成立
当a < b时,有|a-b|=b-a
成立
可以看得出,这种方法的核心就是绝对值,通过绝对值来反转减法的顺序来实现的。
有了最小值,最大值也简单了,因为只有两个数,不是最大就是最小,直接两个数相加,减去最小值,剩下的就是最大值。1
max(a,b)=a+b-min(a,b)
重新定义大于小于
虽然这么说有点奇怪,起码我是想不出什么情况下,最大最小值的定义会先于大于小于出现,并且大于小于还需要通过最大最小值来定义,所以还是不要在意这些细节了。
首先,需要有等于和不等于的定义,a大于b的话,因为只有两个数,所以大于的定义可以变成,a不等于b且a等于a和b中的最大值,同理小于就是等于最小值,应该很好理解,但是没有什么用。
下面是我C++写的代码,写来玩的,重载了一堆运算符,看看就好1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
struct number{
int value;
};
number operator+(const number& A,const number& B){
return number{A.value+B.value};
}
number operator-(const number& A,const number& B){
return number{A.value-B.value};
}
number operator/(const number& A,const int& B){
return number{A.value/B};
}
number abs(const number& A){
return number{abs(A.value)};
}
number min(const number& A,const number& B){
return (A+B-abs(A-B))/2;
}
number max(const number& A,const number& B){
return min(A,B)+abs(A-B);
}
bool operator==(const number& A,const number& B){
return A.value==B.value;
}
bool operator!=(const number& A,const number& B){
return A.value!=B.value;
}
bool operator>(const number& A,const number& B){
return A!=B&&A==max(A,B);
}
bool operator<(const number& A,const number& B){
return A!=B&&A==min(A,B);
}
bool operator>=(const number& A,const number& B){
return A==B||A==max(A,B);
}
bool operator<=(const number& A,const number& B){
return A==B||A==min(A,B);
}
using namespace std;
int main(){
number A{1};
number B{2};
cout<<max(A,B).value<<endl;
return 0;
}