c++ - Result Difference between int and float in Generic Function -
compile , run code; compare result if using integers or floats fractional values. why there difference?
here code:
#include <iostream> using namespace std; template<class t> t find(t array[], t len, t num){ (int = 0; < len; ++i){ if (array[i] == num) return i; } return -1; } int main () { int array1[5] = { 4, 7, 3, 5, 6 }, num1; float array2[5] ={121.2, 111.5, 300.1, 500.1, 600.1 }, num2; cout << "enter int:" << " " ; cin >> num1; cout << "enter float:" << " " ; cin >> num2; int x = find<int>(array1,5,num1); float y= find<float>(array2,5,num2); cout << "the index int is:" << " " << x << endl; cout << "the index float is:" << " " << y << endl; return 0; }
i couldn't find difference between 2 results when using ints , when using floats.
the issue must not compare floats ==
due internal representation of floating point numbers. if using result expression, can mathematically correct find number in array, due limitations in floating point representation ==
not find it.
consider following code:
template<class t> int find(t array[], size_t len, t num){ (size_t = 0; < len; ++i){ cerr << std::setprecision(7) << "compare: " << array[i] << ", " << num; if (array[i] == num) { cerr << " => equal" << endl; return i; } else { cerr << " =>not equal" << endl; } } return -1; } int main () { float array2[2] ={500.1, 1.0 }, num2; float = 500.1 / 2; int = find<float>(array2, 2, 2*a); = 1.0 / 0.3333; = find<float>(array2, 2, * 0.3333); return 0; }
output:
compare: 500.1, 500.1 => equal compare: 500.1, 0.9999999 =>not equal compare: 1, 0.9999999 =>not equal
so, though 1.0 / 0.3333 * 0.3333
1.0
mathematically, not when using floating point arithmetics - 0.99999
instead. therefore ==
not treat numbers equal in last comparison.
to solve this, compare difference of 2 numbers small epsilon
value. float.h
explicitly defines constant flt_epsilon
this:
if (fabs(array[i] - num) < flt_epsilon) { ...
Comments
Post a Comment