rust(13)-闭包作为参数 trait泛型

继续以解一元多次方程割线法为例
下面把闭包作为参数,定义trait泛型:
定义范型,规定该函数的com_fn参数只接受泛型F:Fn(f64)->f64 trait类型


pub fn f_computef64>(com_fn:F,x:f64)->f64{
    com_fn(x)
}

全部代码如下:

  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_computef64>(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()
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>     

你可能感兴趣的:(AI机器学习实战)