tensorflow-不動點迭代求一元方程
阿新 • • 發佈:2018-12-08
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Sep 6 10:16:37 2018 @author: myhaspl @email:[email protected] 不動點法求解f(x)=x """ import tensorflow as tf import numpy as np def f(x): y=tf.cos(x)+tf.sin(x) return y def body(x,fx,tol,i,n): x=f(x) fx=f(x) return (tf.Print(x,[x],"x:"),tf.Print(fx,[fx],"fx:"),tf.Print(tol,[tol],"tol:"),tf.Print(i+1,[i],"i:"),tf.Print(n,[n],"n:")) def c(x,fx,tol,i,n): t1=tf.greater(tf.abs(tf.subtract(fx,x)),tol) t2=tf.less(i,n) return tf.logical_and(t1,t2) x = tf.placeholder(tf.float32,shape=(),name="myx") tol= tf.placeholder(tf.float32,shape=(),name="mytol") fx = tf.constant(0,dtype=tf.float32,name="myfx") i = tf.constant(0,dtype=tf.int32,name="myi") n = tf.constant(0,dtype=tf.int32,name="myn") input_dict={x:0.,fx:np.cos(0)+np.sin(0),tol:1e-8,i:0,n:100} res = tf.while_loop(c, body, loop_vars=[x,fx,tol,i,n]) with tf.Session() as sess: y=sess.run(res,feed_dict=input_dict) print y
tol:[1e-08]
x:[1.25872827]
fx:[1.25872803]
n:[100]
i:[98]tol:[1e-08]x:[1.25872803]
fx:[1.25872827]
n:[100]
x:[1.25872827]i:[99]tol:[1e-08]
fx:[1.25872803]
(1.2587283, 1.258728, 1e-08, 100, 100)