URL: https://www.overclockers.at/coding-stuff/single-precision-saturation_257249/page_1 - zur Vollversion wechseln!
ich habe eine IEEE 754 single precision float x. in einer schleife wird zu x eine zahl y im bereich von 0-32767 addiert. ab welchem wert von x ist
wennCode:x + y = x
meine quick+dirty lösung:
Code: C++#include <math.h> #include <limits> #include <stdio.h> #include <iostream> int main() { float max = std::numeric_limits<float>::max(); float min = 0.0f; float y = 32767; float diff; do { float x = (max - min) / 2.0f; diff = abs(x - (x + y)); if (diff <= std::numeric_limits<float>::epsilon()) max = x; else min = x; } while (diff <= std::numeric_limits<float>::epsilon()); std::cout << max << std::endl; }
Ist das ein IQ-Test oder hast du eine spezielle Frage zur Implementierung? 
Bei float == float musst du immer vorsichtig sein. Wenn es deine Implementierung zulässt, dann entweder < oder > bzw. gewisse Thresholds verwenden (0,1 oder Epsilon zB). Es gibt dazu eine Menge Material online. Ich würde mir Sprachen-spezifische Beispiele dazu anschauen, da es doch teilweise deutliche Unterschiede bzw. auch bereits vorhandene Konstanten gibt.
ich weisZitat aus einem Post von matBei float == float musst du immer vorsichtig sein.
siehe c++ code. die frage war aber absichtlich nicht auf eine bestimmte sprache bezogen. im code oben sind ein paar fehler drin. hier der korrigierte code, nicht dass vinci den nassen fetzen auspackt
Code: C++#include <math.h> #include <limits> #include <stdio.h> #include <iostream> int main() { float max = std::numeric_limits<float>::max(); float min = 0.0f; float y = 32767.0f; float diff; do { float x = (max / 2.0f) + (min / 2.0f); diff = abs(x - (x + y)); if (diff <= std::numeric_limits<float>::epsilon()) max = x; else min = x; } while (abs(max-min) > 2.0f*y); std::cout << max << std::endl; }
overclockers.at v4.thecommunity
© all rights reserved by overclockers.at 2000-2026