根據我的理解,將舍入方向設置爲+Inf
時,將在計算1/3時生成0.333334
,如果將其設置爲-Inf
,則將生成。從Rust和C++設置FPU舍入方向不會改變
當我在C++中使用fesetround(0x400)
和fesetround(0x800)
來嘗試時,情況並非如此。我得到使用FFI魯斯特相同的行爲叫fsetround
從C
C++代碼:
#include <cfenv>
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double ratio = (double)1/(double)10;
fesetround(FE_UPWARD);
cout << fegetround() << " upward " << setprecision(18) << ratio << std::endl;
fesetround(FE_DOWNWARD);
cout << fegetround() << " downward " << setprecision(18) << ratio << std::endl;
return 0;
}
(Pastebin)
鏽代碼:
extern crate libc;
use libc::c_int;
#[link(name = "rounding")]
extern {
pub static fe_upward: c_int;
pub static fe_downward: c_int;
fn fesetround(rount: c_int) -> c_int;
fn fegetround() -> c_int;
}
pub fn upward_round() -> i64 {
unsafe {
fesetround(fe_upward);
fegetround() as i64
}
}
pub fn downward_round() -> i64 {
unsafe {
fesetround(fe_downward);
fegetround() as i64
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_upward() {
unsafe {
assert_eq!(fe_upward as i64, upward_round());
}
}
#[test]
fn test_downward() {
unsafe {
assert_eq!(fe_downward as i64, downward_round());
}
}
}
(Pastebin)
表現形式爲二進制,所以並不那麼簡單,你的C++程序顯示了兩個舍入模式的最後一個數字的區別,所以它似乎正在工作。 – starblue
對我而言對於兩種表示,C++程序的輸出是:0.1000000 ... 006。我知道浮點表示由於其侷限性而只能表示實數的一個子集,通常實際上1/3是0.33333 ...等等。以浮點形式表示需要四捨五入,當我設置四捨五入到+ inf我期望得到0.333334。 –
我得到'0.100000000000000006'和'0.100000000000000005'爲十分之一,'0.333333333333333315'和'0.333333333333333314'爲三分之一。 – starblue