# 在 MQL4 中处理双精度浮点数

12 四月 2016, 12:15
0
2 218

### 简介

MQL 编程为自动化交易提供了新的机遇，世界各地的众多人士已对其表示赞赏。

### 1. 验证数值

```#include <stdlib.mqh>
int start()
{
double a=2.0/3;
Alert("Standard output:",a,", 8 digits precision:",DoubleToStr(a,8),", 15 digits precision:", DoubleToStrMorePrecision(a,15));
return(0);
}
```

```#include <stdlib.mqh>
int start()
{
double a=2.0/100000;
return(0);
}```

### 2. 小数位精确度的准确度

(A/B)*(B)=A,

A-(A/B)*B=0,

(A/B)*(B/A)=1 等

```#include <stdlib.mqh>
int start()
{
int maxfact=23;
double a=1;
for (int i=2; i<=maxfact; i++) { a=a*i; }
for (int j=maxfact; j>=2; j--) { a=a/j; }
return(0);
}```

a=1.0000000000000002

MQL 语言有一个 NormalizeDouble 函数，可以将双精度浮点数圆整为指定的精确度。

```int start()
{
double R=1;
int minpwr=0;
while (R>0) {R=R/10; minpwr--;}
return(0);
}```

### 3. NormalizeDouble 函数

NormalizeDouble (double value, int digits) 函数将浮点数值圆整到给定的精确度。 返回标准化双精度型数值。

```int start()
{
double a=3.141592653589;
return(0);
}```

a=3.14159000

### 4. 检查两个双精度浮点数是否相等

```//+------------------------------------------------------------------+
//| correct comparison of 2 doubles                                  |
//+------------------------------------------------------------------+
bool CompareDoubles(double number1,double number2)
{
if(NormalizeDouble(number1-number2,8)==0) return(true);
else return(false);
}```

```#include <stdlib.mqh>
int start()
{double a=0.123456781;
double b=0.123456782;
}
```

### 5. 整数相除

```int start()
{
return(0);
}
```

```int start()
{ double a=1/3;
double b=1.0/3;
return(0);
}
```

### 6. 整数和双精度浮点数的类型转换

```double xbaseBid=1.2972;
double xBid=1.2973;
double xPoint=0.0001;
int i = 100 + (xBid - xbaseBid)/xPoint;
```

```double baseBid=1.2972,Bid=1.2973,Point=0.0001;
int i = 100 + (Bid - baseBid)/Point;
printf("%d\n",i);```

```double a=0.99999999999999;
int i = 100 + a;

```double a=0.999999999999999;
int i = 100 + a;

```double baseBid=1.2972;
double xBid=1.2973;
double xPoint=0.0001;
int i = 100 + MathRound((xBid - baseBid)/xPoint);

### 7. MathMod 函数的功能

```double MathModCorrect(double a, double b)
{ int tmpres=a/b;
return(a-tmpres*b);
}
```