rust(10)-函数指针
生活随笔
收集整理的這篇文章主要介紹了
rust(10)-函数指针
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
PS F:\learn\rustlearn> rustc learn1.rs
PS F:\learn\rustlearn> .\learn1.exe
0.6823278038280194
PS F:\learn\rustlearn>
函數是一等公民,函數可作為函數的參數和返回值使用。
如下面代碼段所示
完整代碼如下:
use std::f64; pub fn get_next_x(x0:f64,x1:f64)->f64{let res1=&f_compute(fn1,x1);let res0=&f_compute(fn1,x0);x1-res1*((x1-x0)/(res1-res0)) } pub fn f_compute(com_fn:fn(f64)->f64,x:f64)->f64{com_fn(x) }pub fn fn1(x:f64)->f64{x.powi(3)+x-1.0_f64 }fn main() {let tol=1e-8_f64;let x0=0.0_f64;let x1=4.0_f64;let mut x_i:f64=x1;let mut x_isub1:f64=x0;let mut x_iplus1:f64;let mut ans:f64=0.0_f64; let mut finished=false;for _n in 1..200 {x_iplus1=get_next_x(x_isub1,x_i);if (x_iplus1-x_i).abs()<tol { ans=x_iplus1;finished=true;break;} x_isub1=x_i;x_i=x_iplus1;}if finished{println!("{}",ans); } } use std::f64; pub fn get_next_x(com_fn:fn(f64)->f64,x0:f64,x1:f64)->f64{let res1=&f_compute(com_fn,x1);let res0=&f_compute(com_fn,x0);x1-res1*((x1-x0)/(res1-res0)) } pub fn f_compute(com_fn:fn(f64)->f64,x:f64)->f64{com_fn(x) }pub fn fn1(x:f64)->f64{x.powi(3)+x-1.0_f64 } pub fn fn2(x:f64)->f64{2.98*x.powi(3)-5.21*x.powi(2)-7.6_f64 }fn main() {let tol=1e-8_f64;let x0=0.0_f64;let x1=4.0_f64;let mut x_i:f64=x1;let mut x_isub1:f64=x0;let mut x_iplus1:f64;let mut ans:f64=0.0_f64; let mut finished=false;for _n in 1..500 {x_iplus1=get_next_x(fn1,x_isub1,x_i);if (x_iplus1-x_i).abs()<tol { ans=x_iplus1;finished=true;break;} x_isub1=x_i;x_i=x_iplus1;}if finished{println!("{}",ans); }x_i=x1;x_isub1=x0;ans=0.0_f64; finished=false;for _n in 1..200 {x_iplus1=get_next_x(fn2,x_isub1,x_i);if (x_iplus1-x_i).abs()<tol { ans=x_iplus1;finished=true;break;} x_isub1=x_i;x_i=x_iplus1;}if finished{println!("{}",ans); } } PS F:\learn\rustlearn> rustc learn1.rs PS F:\learn\rustlearn> .\learn1.exe 0.6823278038280194 2.2514454804098265 PS F:\learn\rustlearn>總結
以上是生活随笔為你收集整理的rust(10)-函数指针的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java解析多层嵌套json字符串
- 下一篇: 泊松分酒 java课件_泊松分酒原理 -