Jump to content

Recommended Posts

Posted

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,

Posted

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,

Posted

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;
Posted

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 👍

Posted

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 👍

Posted

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,

  • 2 weeks later...
Posted

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

Posted

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

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.