Función POWER T-SQL
Ja... qué sensible resultó la funcioncita de T-SQL para el cálculo de potencias...
¿sensible o "agarrada" (como decimos en México a los que no les gusta la idea de soltar un centavito)?
Pues nada, resulta que en el desarrollo de una aplicación de monitoreo climático de Puebla, uno de los cálculos requería logaritmos y potencias. Parecía que todo resultaba bien, pero a la hora de corroborar resultados, el dichoso (ni tanto) cálculo tenía un desfasamiento importante, entonces buscando y rebuscando nos dimos cuenta que la culpa era de la función POWER.
Resulta que esta función que recibe como parámetros una base y un exponente, cuando la base es entera, no importa que el exponente sea fraccionario (con punto decimal o flotante, que es lo mismo), el resultado que devuelve es entero ¿solución? un casteo o conversión a float de la base o agregarle un punto y tantos ceros como decimales queremos que nos regrese.
POWER(10, @ExponenteDecimal) | resultado entero |
POWER(CAST(10 as float), @ExponenteDecimal) | resultado con punto flotante |
POWER(10.0, @ExponenteDecimal) | resultado con 1 decimal luego del punto. |
Tos comentarios me ayudan a mejorar el contenido de mis publicaciones para que sean de mayor utilidad e interés. Agradezco tu aportación.
Ha... How sensitive it turner out the little T-SQL function for power calculation...
sensitive or "mean"? (As we say in Mexico about people who doesn't like the idea of spending a penny)
Because nothing, results that during the development for a Puebla's weather monitor application, one of the operations required to use logarithms and powers. It looks like everything goes well, but at the moment of verify results, the meant calculus had an important defase, then, searching once and again for the answer we noticed that the guilty was the POWER function.
It turns out that this function recieve as parameters a base and an exponent, when the base is integer, it doesn't matter if the exponent is fractionary (with decimal or floating point, what is the same), the result that returns is integer. Solution? a cast or data convertion to float of the base, or we add a decimal separator and as many zeroes as the result we want.
POWER(10, @DecimalExponent) | Integer result |
POWER(CAST(10 as float), @DecimalExponent) | Floating point result |
POWER(10.0, @DecimalExponent) | Result withn 1 decimal after the point. |
Questions?
Comentarios
Publicar un comentario