有沒有什麼聰明的方法來解決這個問題?智能的方式來做近似int溢出計算
uint32_t a = 16637510;
uint32_t b = 45627362;
uint32_t c = 0;
c = a * 100000/b //overflows
c = (a * 100/b)*1000 //gives 36000
我需要得到結果c = 36463或更好36464.並且需要快速,非浮動操作。 CPU是STM32F4
更新:
接受的答案被轉換爲100000〜100000ULL(64位),但作爲@PeterJ建議(和刪除他的回答)使用STM32F4 FPU是更快然後除以64點的操作
Timer t;
int i;
t.start();
for(i = 1; i <= 100000; ++i) c = a * 100000ULL/b;
t.stop();
printf("64\ttakes %f seconds, du is %d\n", t.read(), c);
t.reset();
t.start();
for(i = 1; i <= 100000; ++i) c = (uint32_t)((float)a * 100000.0f/(float)b);
t.stop();
printf("float\ttakes %f seconds, du is %d\n", t.read(), c);
t.reset();
64需要0.086669秒,杜是57333
浮子需要0.017779秒,杜是57333
不用擔心。你不喜歡它 - 我把它刪除:) –
只有大概的32位數學解決方案存在。 'a,b'的範圍是什麼?什麼是容忍誤差(+/- 1?) – chux
溢出有多常見?他們是一個例外,還是他們發生在每個數據集? – ensc