在#[no_std]下执行数学运算

如果你想要执行数学相关的函数,像是计算平方根或者一个数的指数且你有完整的标准库支持,你的代码可能看起来像这个:

  1. //! 可用一些标准支持的数学函数
  2. fn main() {
  3. let float: f32 = 4.82832;
  4. let floored_float = float.floor();
  5. let sqrt_of_four = floored_float.sqrt();
  6. let sinus_of_four = floored_float.sin();
  7. let exponential_of_four = floored_float.exp();
  8. println!("Floored test float {} to {}", float, floored_float);
  9. println!("The square root of {} is {}", floored_float, sqrt_of_four);
  10. println!("The sinus of four is {}", sinus_of_four);
  11. println!(
  12. "The exponential of four to the base e is {}",
  13. exponential_of_four
  14. )
  15. }

没有标准库支持的时候,这些函数不可用。反而可以使用像是libm这样一个外部库。示例的代码将会看起来像这样:

  1. #![no_main]
  2. #![no_std]
  3. use panic_halt as _;
  4. use cortex_m_rt::entry;
  5. use cortex_m_semihosting::{debug, hprintln};
  6. use libm::{exp, floorf, sin, sqrtf};
  7. #[entry]
  8. fn main() -> ! {
  9. let float = 4.82832;
  10. let floored_float = floorf(float);
  11. let sqrt_of_four = sqrtf(floored_float);
  12. let sinus_of_four = sin(floored_float.into());
  13. let exponential_of_four = exp(floored_float.into());
  14. hprintln!("Floored test float {} to {}", float, floored_float).unwrap();
  15. hprintln!("The square root of {} is {}", floored_float, sqrt_of_four).unwrap();
  16. hprintln!("The sinus of four is {}", sinus_of_four).unwrap();
  17. hprintln!(
  18. "The exponential of four to the base e is {}",
  19. exponential_of_four
  20. )
  21. .unwrap();
  22. // 退出QEMU
  23. // 注意不要在硬件上允许这个; 它能破坏OpenOCD的状态
  24. // debug::exit(debug::EXIT_SUCCESS);
  25. loop {}
  26. }

如果你需要在你的MCU上执行更复杂的操作,像是DSP信号处理或者更高级的线性代数,下列的crates可能可以帮到你