Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
w = sqrt(t1*t1-(b*(-b)-t2*(a+t1)));
w = sqrt(t1*t1+(b*b+t2*(a+t1)));
#include <iostream>
#include <stdint.h>
int main()
{
uint64_t a_pos= 0x7FFFFFFFFFFFFFFFUL;
uint64_t a_neg= 0xFFFFFFFFFFFFFFFFUL;
double *a, *b;
a = (double*)&a_pos;
b = (double*)&a_neg;
std::cout << *a << " " << *b << " " << *a+*b << std::endl;
a_pos = - a_pos;
a_neg = - a_neg;
std::cout << *a << " " << *b << " " << *a+*b << std::endl;
a_pos = - a_pos;
a_neg = - a_neg;
std::cout << *a << " " << *b << " " << *a+*b << std::endl;
return 0;
}
$ ./a.out
nan -nan nan
-4.94066e-324 4.94066e-324 0
nan -nan nan
$
This is the length of the hypotenuse of a right-angled triangle with sides of length x and y, or the distance of the point (x,y) from the origin (0,0), or the magnitude of a complex number x+iy
max = maximum(|x|, |y|);
min = minimum(|x|, |y|);
r = min / max;
return max*sqrt(1 + r*r);
max = maximum(x, y);
min = minimum(x, y);
r = min / max;
return max*sqrt(1 + r*r);
0, то алгоритм работает правильно, но если обе стороны по нулям, то алгоритм должен вернуть 0, разве нет? Или предполагается что это очевидная вещь и проверки должны написать сами?— The _hypot function calculates the length of the hypotenuse of a right triangle, given the length of the two sides x and y (in other words, the square root of x^2 + y^2).У меня в
— Треугольник это термин. Треугольник это геометрическая фигура, образованная тремя отрезками, которые соединяют три не лежащие на одной прямой точки. Из этого определение следует, что нет ситуации, когда у треугольника хотя бы одна сторона имеет нулевую длину, а когда такая ситуация наступает, то треугольник перестает быть таковым, даже сам смысл термина гипотенуза в таком случае теряется.
man hypot написано прямо в заголовке: «hypot, hypotf, hypotl - Euclidean distance function». И ниже:The hypot() function returns sqrt(x*x+y*y). This is the length of the hypotenuse of a right-angled triangle with sides of length x and y, or the distance of the point (x,y) from the origin.В стандарте (POSIX) написано точно тоже самое. Так что ваша функция обязана отрабатывать ноль правильно.hypot, hypotf, hypotl — Euclidean distance functionи
These functions shall compute the value of the square root of x²+y² without undue overflow or underflow., но ниже только
Upon successful completion, these functions shall return the length of the hypotenuse of a right-angled triangle with sides of length x and y.
N ^ P mod M. В криптографические библиотеки для этого добавляют специально оптимизированную функцию modexp.mod M). Оптимизация позволяет этого избежать.__int64 FastPow (__int64 a, __int64 x, __int64 p)
{
__int64 res = 1, s = a;
while (x) {
if (x % 2 == 1)
res = res * s % p;
s = s * s % p;
x /= 2;
}
return res;
}
hypot(x, y) в 10-20 раз (тестировал на Visual Studio C++ 2010 и MinGW 4.7.2) медленнее наивного рукописного варианта?inline double naive_hypot(double x, double y)
{
return sqrt(x * x + y * y);
}
sqrt(x * x + y * y).r = min / max;sqrt(x * x + y * y); тоже получается в этом случае, что мы очень большое складываем с очень маленьким и где будет больше потеря точности с ходу непонятно.
x=1, y=123123123123sqrt(x * x + y * y);
r = min / max;

function hypo1 (x,y) {
return Math.sqrt(x*x+y*y);
}
function hypo2 (x,y) {
var i, a, r;
x = Math.abs(x);
y = Math.abs(y);
a = Math.max(x,y);
i = Math.min(x,y);
r = i / a;
return a*Math.sqrt(1 + r*r);
}
var
x = 100000013,
y = 13;
console.log( hypo1(x,y) ); // 100000013.00000083
console.log( hypo2(x,y) ); // 100000013.00000085
var
x = 221412142513,
y = 1242353;
console.log( hypo1(x,y) ); // 221412142516.48547
console.log( hypo2(x,y) ); // 221412142516.48544
|x| * |y|?double FSqrt(double x){
double y=x;
((int*)&y)[1]=(((int*)&x)[1]>>1)+0x1FF76CF6;
y=(y+x/y)*0.5;
y=(y+x/y)*0.5;
y=(y+x/y)*0.5;
return y;
}
double Hypo(double a,double b){
int ca=((int*)&a)[1]&0x7ff00000,cb=((int*)&b)[1]&0x7ff00000;
const int maxdif=0x1e00000; // 2^-30
if(ca-cb>maxdif) return fabs(a);
if(cb-ca>maxdif) return fabs(b);
if(ca<cb) ca=cb;
ca-=0x40000000;
((int*)&a)[1]-=ca; ((int*)&b)[1]-=ca;
double x=a*a+b*b;
double x2=x*0.5,y=0;
((int*)&y)[1]=0x5fe6eb50-(((int*)&x)[1]>>1);
y*=1.5-x2*y*y;
y*=1.5-x2*y*y;
y*=1.5-x2*y*y;
y*=1.5-x2*y*y;
y*=x;
((int*)&y)[1]+=ca;
return y;
}
Что сложного может быть в вычислении гипотенузы?