c++ - float to int conversion going wrong (even though the float is already an int) -
i writing little function calculate binomial coefficiant using tgamma function provided c++. tgamma returns float values, wanted return integer. please take @ example program comparing 3 ways of converting float int:
#include <iostream> #include <cmath> int bincoeffnear(int n,int k){ return std::nearbyint( std::tgamma(n+1) / (std::tgamma(k+1)*std::tgamma(n-k+1)) ); } int bincoeffcast(int n,int k){ return static_cast<int>( std::tgamma(n+1) / (std::tgamma(k+1)*std::tgamma(n-k+1)) ); } int bincoeff(int n,int k){ return (int) std::tgamma(n+1) / (std::tgamma(k+1)*std::tgamma(n-k+1)); } int main() { int n = 7; int k = 2; std::cout << "correct: " << std::tgamma(7+1) / (std::tgamma(2+1)*std::tgamma(7-2+1)); //returns 21 std::cout << " bincoeff: " << bincoeff(n,k); //returns 20 std::cout << " staticcast: " << bincoeffcast(n,k); //returns 20 std::cout << " nearby int: " << bincoeffnear(n,k); //returns 21 return 0; }
why it, though calculation returns float equal 21, 'normal' conversion fails , nearbyint returns correct value. nicest way implement this?
edit: according c++ documentation here tgamma(int) returns double.
from this std::tgamma
reference:
if arg natural number,
std::tgamma(arg)
factorial of arg-1. many implementations calculate exact integer-domain factorial if argument sufficiently small integer.
it seems compiler you're using doing that, calculating factorial of 7
expression std::tgamma(7+1)
.
the result might differ between compilers, , between optimization levels. demonstrated jonas there big difference between optimized , unoptimized builds.
wiki
Comments
Post a Comment