maiden Posted June 30, 2006 at 10:50 PM Report #35744 Posted June 30, 2006 at 10:50 PM Boas, Aqui ficam algumas funções que permitem o cálculo da raiz de um numero, em várias linguagens de programação. Baseado no Algoritmo de Fixed Point. C/C++: double sqrt(int x) { double aproximacao = 0.0000001; double valor1 = 1.0; double valor2 = 0; do { valor2 = valor1; valor1 = (valor1 + (x/valor1))/2; } while (abs(valor1 - valor2) > aproximacao); return valor1; } Kids Programming Language: Function mysqrt (num As Int) As Decimal Var estimativa As Decimal Var a As Decimal Var b As Decimal estimativa = 0.0000001 a = 1.0 b = 0 While (Abs(a-b)>estimativa) b=a a=(a+(num/a))/2 End While Return a End Function LISP: (defconstant +estimativa+ 0.00000001) (defun fixed-point (funcao estimativa) (labels ((good-enough-p (value1 value2) (< (abs (- value1 value2)) +estimativa+)) (iteration (guess) (let ((new-guess (funcall funcao guess))) (if (good-enough-p new-guess guess) new-guess (iteration new-guess))))) (iteration estimativa))) (defun my-sqrt (x) (fixed-point (lambda (y) (/ (+ y (/ x y)) 2)) 1.0)) Pascal: function sqrt2(x:integer):real; var aprox,a,b:real; begin aprox:=0.0000001; a:=1.0; b:=0; repeat b:=a; a:=(a+(x/a))/2; until (abs(a-b)<=aprox); sqrt2:=a; end; PHP: function sqrt($x) { $aproximacao = 0.0000001; $valor1 = 1.0; $valor2 = 0; while (abs($valor1-$valor2) > $aproximacao) { $valor2 = $valor1; $valor1 = ($valor1 + ($x/$valor1))/2; } return $valor1; } Python: estimativa = 0.000001 def goodp2(value1, value2): return abs(value1 - value2) < estimativa def iter2(guess,f): next = f(guess) if goodp2(guess,next): return next else: return iter2(next,f) def fixed_point(f,guess): return iter2(guess,f) def my_sqrt2(x): return fixed_point(lambda (y) :(y + (x / y))/2, 1.0) print my_sqrt2(16) Ruby: def abs(x) return -x if x < 0 x end def sqrt(x) aproximacao = 0.000001 valor1 = 1.0 valor2 = 2.0 while abs(valor1 - valor2) > aproximacao valor2 = valor1 valor1 = (valor1 + (x / valor1)) /2 end valor1 end mIRC Scripting: alias sqrt2 { var %aprox = 0.00001 var %a = 1.0 var %b = 0 while ($abs($calc(%a - %b)) > %aprox) { set %b %a set %a $calc($calc(%a + $calc($$1 / %a)) / 2) } return %a } Códigos por yin, neon_prannock, MAiDEN_DuDE, Warrior e QuickFire. Brevemente espero colocar em mais linguagens. Cumps,
UnKnowN Posted July 1, 2006 at 08:29 AM Report #35774 Posted July 1, 2006 at 08:29 AM Existe uma função para isso em Python pelo menos : >>> import math >>> math.sqrt(9) 3.0 >>> from math import sqrt >>> sqrt(9) 3.0
maiden Posted July 1, 2006 at 12:49 PM Author Report #35788 Posted July 1, 2006 at 12:49 PM Sim, o pessoal sabia disso. Mas o interessante foi tentar calcular a raiz sem nenhuma função predefinida, ou seja criarmos a nossa própria função. O objectivo, mais do que calcular a raiz quadrada de um numero, é demonstrar os cálculos necessários para o fazer, em várias linguagens. ? Cumps,
Warrior Posted July 1, 2006 at 01:08 PM Report #35794 Posted July 1, 2006 at 01:08 PM já não pegava em pascal há bastante.. function sqrt2(x:integer):real; var aprox,a,b:real; begin aprox:=0.0000001; a:=1.0; b:=0; repeat b:=a; a:=(a+(x/a))/2; until (abs(a-b)<=aprox); sqrt2:=a; end;
UnKnowN Posted July 1, 2006 at 01:16 PM Report #35796 Posted July 1, 2006 at 01:16 PM Sim, o pessoal sabia disso. Mas o interessante foi tentar calcular a raiz sem nenhuma função predefinida, ou seja criarmos a nossa própria função. O objectivo, mais do que calcular a raiz quadrada de um numero, é demonstrar os cálculos necessários para o fazer, em várias linguagens. ? Cumps, Ok got it 👍 PS: Bom Post 👍
QuickFire Posted July 1, 2006 at 01:27 PM Report #35797 Posted July 1, 2006 at 01:27 PM Em php também é facil B) function sqrt($x) { $aproximacao = 0.0000001; $valor1 = 1.0; $valor2 = 0; while (abs($valor1-$valor2) > $aproximacao) { $valor2 = $valor1; $valor1 = ($valor1 + ($x/$valor1))/2; } return $valor1; } Código corrigido 👍 Thanks m8 👍
neon_prannock Posted July 1, 2006 at 01:29 PM Report #35798 Posted July 1, 2006 at 01:29 PM Continuem a adicionar novas linguagens... Isto surgiu de um desafio no canal #p@p NOTA: o código em php precisa que a subtracção dos dois valores de um resultado absoluto, usando abs(), para o código funcionar correctamente... http://sergiosantos.info http://ideias3.com http://takeoff.ideias3.com
maiden Posted July 1, 2006 at 03:04 PM Author Report #35809 Posted July 1, 2006 at 03:04 PM Adicionado código em KPL, da minha autoria. P.S.: Devido ao GeSHi não ter uma opção para colocar código em KPL adicionei-o sob a forma de código em Pascal. Cumps,
neon_prannock Posted July 5, 2006 at 10:00 PM Report #36456 Posted July 5, 2006 at 10:00 PM A função sqrt em Ruby, com a respectiva função abs. Ruby: def abs(x) return -x if x < 0 x end def sqrt(x) aproximacao = 0.000001 valor1 = 1.0 valor2 = 2.0 while abs(valor1 - valor2) > aproximacao valor2 = valor1 valor1 = (valor1 + (x / valor1)) /2 end valor1 end http://sergiosantos.info http://ideias3.com http://takeoff.ideias3.com
neon_prannock Posted July 5, 2006 at 10:18 PM Report #36463 Posted July 5, 2006 at 10:18 PM Uma nova versão, optimizada, com menos uma variável. Ruby optimized def sqrt(x) aproximacao = 0.0000001 valor1 = 1.0 valor1 = (valor1 + (x / valor1))/2 while abs(valor1 - ((valor1 + (x / valor1))/2)) > aproximacao valor1 end http://sergiosantos.info http://ideias3.com http://takeoff.ideias3.com
skin Posted July 16, 2006 at 09:23 PM Report #38538 Posted July 16, 2006 at 09:23 PM Gostei 🙂 Our lives begin to end the day we become silent about things that matter - Martin Luther King
saramgsilva Posted July 18, 2006 at 09:08 AM Report #38797 Posted July 18, 2006 at 09:08 AM Bem, voces andaram a brincar com a raiz quadrada...gostei dos vossos exemplos, este programa faz-se muito quando estamos a iniciar alguma linguagem de programação... 😛 www.saramgsilva.com As minhas apps no WP7 Marketplace Youtube : Galinho - Windows Phone 7.5
HecKel Posted July 20, 2006 at 05:29 PM Report #39264 Posted July 20, 2006 at 05:29 PM série de taylor rulla para isto 🙂 Quero ver se consigo aplicar em PROLOG e depois espeto aqui 😄 abraços, HecKel Look Left Blog
Warrior Posted July 20, 2006 at 09:34 PM Report #39306 Posted July 20, 2006 at 09:34 PM Passei por este tópico e lembrei-me de mais uma contribuição.. Considerem isto linguagem só se quiserem (eu não considero..) mIRC Scripting: alias sqrt2 { var %aprox = 0.00001 var %a = 1.0 var %b = 0 while ($abs($calc(%a - %b) > %aprox) { set %b %a set %a $calc($calc(%a + $calc($$1 / %a)) / 2) } return %a } Estou enferrujado, portanto não sei se não haverá nenhum método mais simples
Rui Carlos Posted July 24, 2006 at 11:16 PM Report #40068 Posted July 24, 2006 at 11:16 PM parece que ainda não temos a versão em Haskell... sqrt::Double->Double sqrt x=sqrt' x 1 where sqrt' x v=if abs (v-(v+x/v)/2) > 1/10^12 then sqrt' x ((v+x/v)/2) else v fica aqui também a versão em MatLab function r=rsqrt(x) v=1; ap=10^-12; while abs(v-(v+x/v)/2)>ap v=(v+x/v)/2; end r=v; Rui Carlos Gonçalves
HecKel Posted July 25, 2006 at 12:23 AM Report #40074 Posted July 25, 2006 at 12:23 AM Em PROLOG 🙂 sqrt(N,S) :- loop(N, 0, 1, 1, S). loop(N, Sqrt, Odd, Sum, Ans) :- Sum =< N, Sqrt1 is Sqrt+1, Odd1 is Odd+2, Sum1 is Sum+Odd, loop(N, Sqrt1, Odd1, Sum1, Ans). loop(N, Sqrt, _, Sum, Sqrt) :- Sum > N. Como o GeSHi não tem sintaxe de PROLOG..., fica mesmo sem sintaxe 😞 abraços, HecKel Look Left Blog
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now