Created
November 21, 2022 10:37
-
-
Save dascandy/ac4b6a0e86c5edc10d7395f689687fb0 to your computer and use it in GitHub Desktop.
float roundtrip conversion test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <atomic> | |
| #include <vector> | |
| #include <thread> | |
| #include <string> | |
| #include <cstdio> | |
| #include <charconv> | |
| bool test(float f) { | |
| #if 0 | |
| float f2 = std::stof(std::to_string(f)); | |
| return (f == f2); | |
| #else | |
| char buffer[40]; | |
| float f2; | |
| auto res = std::to_chars(buffer, buffer+sizeof(buffer), f); | |
| auto res2 = std::from_chars(buffer, res.ptr, f2); | |
| return f == f2; | |
| #endif | |
| } | |
| int main() { | |
| std::atomic<size_t> failcount; | |
| std::vector<std::thread> threads; | |
| threads.reserve(std::thread::hardware_concurrency()); | |
| for (size_t n = 0; n < threads.capacity(); n++) { | |
| threads.emplace_back([&,id = n]{ | |
| size_t fails = 0; | |
| for (uint32_t top = 0x0; top != 0xFF000000; top += 0x800000) { | |
| for (uint32_t i = (id << 18); i < ((id+1) << 18); i++) { | |
| uint32_t val = i + top; | |
| float f; | |
| memcpy(&f, &val, 4); | |
| if (not test(f)) fails++; | |
| } | |
| } | |
| failcount += fails; | |
| printf("Thread %zu failed %zu\n", id, fails); | |
| }); | |
| } | |
| size_t fails2 = 0; | |
| for (uint32_t val : { 0x7F800000U, 0x7F800001U, 0xFF800000U, 0xFF800001U }) { | |
| float f; | |
| memcpy(&f, &val, 4); | |
| if (not test(f)) fails2++; | |
| } | |
| printf("nan/inf %zu failed\n", fails2); | |
| failcount += fails2; | |
| for (auto& t : threads) t.join(); | |
| printf("%zu fail\n", failcount.load()); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment