2016-04-11 11 views
0

たとえば、アップキャストのための自動浮動小数点(テンプレート)プレースホルダがありますか? int型?私は、パラメータを取り、自動アップキャストを考慮した適切なサイズの浮動小数点型を返すクラスや何かを意味します。cxx11の浮動小数点型(アップキャスト)に整数

私は行が気に入らない。なぜなら、intの場合、正しいタイプの変換はdoubleになるからです。この例では

if(is_equal((float)var_high, (float)var_low)) { 

template <class T> 
T linear_interpolate(const T &low_output, const T &high_output, 
        const T &var_value, 
        const T &var_low, const T &var_high) 
{ 
    if (var_value <= var_low) { 
     return low_output; 
    } 
    if (var_value >= var_high) { 
     return high_output; 
    } 
    // avoid zero divisions or zero like divisions 
    if(is_equal((float)var_high, (float)var_low)) { 
     return low_output; 
    } 

    T p = (var_value - var_low)/(var_high - var_low); 
    return low_output + p * (high_output - low_output); 
} 
+0

「int型の場合は、変換のための右のタイプは、二重になります」。どうして? – 101010

+0

@ 101010フロートが十分な精度を持たないことを意味すると思います(両方とも32ビットと考える)。 –

+0

キーワード、関数、または自動的に正しい型(float、double、long double ..)を自動的に挿入するクラスを探していました – dgrat

答えて

0

あなたはそのタイプの最小表現に(高 - 低)の違いを比較することができます:

if (var_high - var_low <= std::numeric_limits<T>::epsilon()) 

をまた変更する必要がありますintとの演算 - が整数型の場合、一時変数pは常にゼロになります。

完全なコード、いくつかのテストで:

#include <limits> 

template <class T> 
T linear_interpolate(const T &low_output, const T &high_output, 
        const T &var_value, 
        const T &var_low, const T &var_high) 
{ 
    if (var_value <= var_low) { 
     return low_output; 
    } 
    if (var_value >= var_high) { 
     return high_output; 
    } 
    // avoid zero divisions or zero like divisions 
    if (var_high - var_low <= std::numeric_limits<T>::epsilon()) { 
     return low_output; 
    } 

    return low_output 
     + (var_value - var_low) * (high_output - low_output)/(var_high - var_low); 
} 


#include <iostream> 
int main() 
{ 
    std::cout << linear_interpolate(1, 10, 6, 0, 9) << std::endl; 
    std::cout << linear_interpolate(1, 10, 0, 0, 0) << std::endl; 
    std::cout << linear_interpolate(1, 10, 1, 0, 1) << std::endl; 

    std::cout << linear_interpolate(1.0, 10.0, 6.0, 0.0, 9.0) << std::endl; 
    std::cout << linear_interpolate(1.0, 10.0, 0.0, 0.0, 0.0) << std::endl; 
    std::cout << linear_interpolate(1.0, 10.0, 1.0, 0.0, 1.0) << std::endl; 
} 

私はあなたがすでにそれらの持っていると仮定して、私は、value<lowなどのテストを含めていません。


おそらく、線形補間は、入力と出力のためのさまざまな種類を望む可能性が高いことを考慮するべきである:

template <class T, class S=T> 
S linear_interpolate(const S &low_output, const S &high_output, 
        const T &var_value, 
        const T &var_low, const T &var_high) 
+0

ユーザが整数を挿入する場合、ハード整数のゼロとε(浮動小数点)を比較します。これによりアップキャストが発生する可能性があります。 – dgrat

+0

@dgrat、trueではない - 'std :: numeric_limits :: epsilon()'は 'T'を返します。 –

関連する問題