tensorflow-不动点迭代求一元方程
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了tensorflow-不动点迭代求一元方程相关的知识,希望对你有一定的参考价值。
#!/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)
以上是关于tensorflow-不动点迭代求一元方程的主要内容,如果未能解决你的问题,请参考以下文章