rust(13)-闭包作为参数 trait泛型
生活随笔
收集整理的這篇文章主要介紹了
rust(13)-闭包作为参数 trait泛型
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
繼續以解一元多次方程割線法為例
下面把閉包作為參數,定義trait泛型:
定義范型,規定該函數的com_fn參數只接受泛型F:Fn(f64)->f64 trait類型
全部代碼如下:
use std::f64; pub fn get_next_x(com_fn:impl 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<F:Fn(f64)->f64>(com_fn:F,x:f64)->f64{com_fn(x) }pub fn get_fn(i:i32)->impl Fn(f64)->f64{let my_fn=move |x:f64|->f64 {x.powi(i+1)+x.powi(i)-1.0_f64};my_fn }fn main() {let tol=1e-8_f64;let x0=-10.0_f64;let x1=10.0_f64;let mut x_i:f64;let mut x_isub1:f64;let mut x_iplus1:f64;let mut ans:f64; let mut finished;let mut fn_comp;for i in 1..20{fn_comp=get_fn(i);x_i=x1;x_isub1=x0;ans=0.0_f64; finished=false; for _n in 1..2000 {x_iplus1=get_next_x(&fn_comp,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!("function{},解:{}",i,ans); }else{println!("function{},找不到解",i); } } } PS F:\learn\rustlearn> rustc learn8.rs PS F:\learn\rustlearn> .\learn8.exe function1,解:0.6180339887498948 function2,解:0.7548776662466918 function3,解:0.8191725133961645 function4,解:0.0012008970334152279 function5,解:0.8812714616336657 function6,解:0.00001800013706088066 function7,解:0.9115923534820559 function8,解:-0.999999980000001 function9,解:0.9295701282320228 function10,解:-0.9999999998 function11,解:10.000000000244464 function12,解:-0.9999999999979999 function13,解:10.000000000002444 function14,解:-0.9999999999999793 function15,解:10.000000000000027 function16,解:-0.9999999999999999 function17,解:9.999999999999986 function18,解:-1 function19,解:10 PS F:\learn\rustlearn>總結
以上是生活随笔為你收集整理的rust(13)-闭包作为参数 trait泛型的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: excel 图片转url_最全总结 |
- 下一篇: JVM中的五大内存区域划分详解