4 Replies - 1253 Views - Last Post: 17 February 2010 - 11:45 PM

#1 erik.price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 486
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

[Google Go] Newton-Rhapson Square Root

Posted 30 January 2010 - 11:28 AM

Description: Calculates the square root of a given number.
func newtonSqrt(x float, epsilon float) float {
	
	var (
		ctr int; 
		guess = 10.0;
		result = guess - ( ( guess * guess - x ) / ( 2 * guess ) )
	)
	
	if x < 0  {
		return -1.0
		//negative square roots don't have a solution (at least a real one, anyway)
	} else if x == 0{
		return 0
	}
	
	for (dblAbs( result * result - x) > epsilon && ctr < 1000) { 
		guess = result
		result = guess - ( ( guess * guess - x ) / ( 2 * guess ) )
		ctr = ctr + 1
	}
	
	return result
}

func dblAbs(x float) float { //there probably is a way to use absolute value with doubles, but I couldn't find it
	if x < 0 {
		return -1 * x
	}
	return x
}


Is This A Good Question/Topic? 0
  • +

Replies To: [Google Go] Newton-Rhapson Square Root

#2 Huzi94  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 14
  • View blog
  • Posts: 119
  • Joined: 14-November 09

Re: [Google Go] Newton-Rhapson Square Root

Posted 31 January 2010 - 01:35 AM

Great snippet! Can you help me with Google Go tutorials
Was This Post Helpful? 0
  • +
  • -

#3 erik.price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 486
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

Re: [Google Go] Newton-Rhapson Square Root

Posted 31 January 2010 - 08:49 AM

I actually just started learning it yesterday, so I might not be the best choice for writing a tutorial. Go to golang.org and check out Effective Go. That seems like a pretty thorough resource http://golang.org/do...fective_go.html Good luck!
Was This Post Helpful? 0
  • +
  • -

#4 Huzi94  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 14
  • View blog
  • Posts: 119
  • Joined: 14-November 09

Re: [Google Go] Newton-Rhapson Square Root

Posted 31 January 2010 - 09:29 AM

Thanks!
Was This Post Helpful? 0
  • +
  • -

#5 Raynes  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 614
  • View blog
  • Posts: 2,815
  • Joined: 05-January 09

Re: [Google Go] Newton-Rhapson Square Root

Posted 17 February 2010 - 11:45 PM

Cool. I need to check this language out sometime. I've been busy with Factor, Ioke (which I might help develop soon), Clojure, etc.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1