double - одинаковые вычисления, разные результаты
От: What Беларусь  
Дата: 12.12.04 12:17
Оценка: 98 (10)
#Имя: FAQ.cpp.double.Op
Здравствуйте, Yozh_Programmer, Вы писали:

Y_P>Почему этот код



Y_P>
Y_P>#include <windows.h>
Y_P>#include <stdio.h>
Y_P>#define _USE_MATH_DEFINES
Y_P>#include <math.h>
Y_P>#include <conio.h>

Y_P>const double Log10 = log(10.0);

Y_P>int main()
Y_P>{
Y_P>    int x = 100;
Y_P>    printf("%.20f\n\n", log((double)x) / Log10);
Y_P>    printf("%.20f\n\n", log((double)x) / Log10);
Y_P>    while (!kbhit()) {}
Y_P>}
Y_P>


Y_P>выдает такие результаты


Y_P>1.99999999999999980000


Y_P>2.00000000000000000000


Если хочешь, чтобы результаты были одинаковые — используй опцию компиляции /Op (Improve Float Consistency)
Из MSDN:

This option improves the consistency of floating-point tests for equality and inequality by disabling optimizations that could change the precision of floating-point calculations.

By default, the compiler uses the coprocessor's 80-bit registers to hold the intermediate results of floating-point calculations. This increases program speed and decreases program size. However, because the calculation involves floating-point data types that are represented in memory by less than 80 bits, carrying the extra bits of precision (80 bits minus the number of bits in a smaller floating-point type) through a lengthy calculation can produce inconsistent results.

With /Op, the compiler loads data from memory prior to each floating-point operation and, if assignment occurs, writes the results back to memory upon completion. Loading the data prior to each operation guarantees that the data does not retain any significance greater than the capacity of its type.

A program compiled with /Op may be slower and larger than one compiled without /Op.

... << RSDN@Home 1.1.4 beta 3 rev. 185>>
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.