1. 程式人生 > >tensorflow-二分法求解一元方程

tensorflow-二分法求解一元方程

tensorflow程式設計還是比較麻煩~

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 24 08:25:41 2017
f(x)=x^3+2*(x^2)-45=0
二分法求解一元方程
@author: [email protected]
"""
import tensorflow as tf

def fp(x):
    return tf.subtract(tf.add(tf.pow(x,3),tf.multiply(tf.pow(x,2),2.)),45.)

i=tf.Variable(1,dtype=tf.int32)
MIN_RESULT=-10.
MAX_RESULT=10.
a=tf.constant(MIN_RESULT,dtype=tf.float32)
b=tf.constant(MAX_RESULT,dtype=tf.float32)
n=tf.constant(300)
result=tf.Variable([],dtype=tf.float32)
x_result=tf.Variable(MIN_RESULT-1,dtype=tf.float32)
fa_result=tf.Variable(fp(MIN_RESULT),dtype=tf.float32)

TOL=1e-6
#本部落格所有內容是原創,如果轉載請註明來源http://blog.csdn.net/myhaspl/    

def fp_cond(i,n,a,b,result,fa_result,x_result):
    return tf.logical_and(tf.less(i,n),tf.less(x_result,MIN_RESULT))

def fp_body(i,n,a,b,result,fa_result,x_result):
    p=tf.add(a,tf.divide((b-a),2.))

    fp_result=fp(p)
    x_result=tf.cond(tf.logical_or(tf.equal(fp_result,0),tf.less((b-a)/2.,TOL)),lambda:p,lambda:MIN_RESULT-1)
    result=tf.concat([[a,b,x_result],result],axis=0) 

    [a,b,fa_result]=tf.cond(tf.greater(tf.multiply(fa_result,fp_result),0),\
            lambda:[p,b,fp_result],\
            lambda:[a,p,fa_result])
    i=i+1
    return i,n,a,b,result,fa_result,x_result

init_assign = tf.global_variables_initializer()
i,n,a,b,result,fa_result,x_result=tf.while_loop(fp_cond,fp_body,\
                                     loop_vars=[i,n,a,b,result,fa_result,x_result],\
                                     shape_invariants=[i.get_shape(),n.get_shape(),a.get_shape(),b.get_shape(),tf.TensorShape([None]),fa_result.get_shape(),x_result.get_shape()]) 

with tf.Session() as sess:
    sess.run(init_assign)    
    sess.run([i,n,a,b,result,fa_result,x_result])
    print "在",sess.run(result[0]),"-",sess.run(result[1]),"內:"
    print sess.run(i),"次迭代,計算方程的解:",sess.run(result[2])