안녕하세요 여러분, 수업 시간에 숫자 제곱근을 만들어야하지만 작동하지 않습니다!
도전 과제 :
Write a function or program that will "make a number square root".
참고 : 이것은 코드 트롤링입니다. 이 새로운 프로그래머에게 프로그래밍 성공의 길을 안내하는 "유용한"답변을 제공하십시오! 창의력을 발휘하십시오!
안녕하세요 여러분, 수업 시간에 숫자 제곱근을 만들어야하지만 작동하지 않습니다!
도전 과제 :
Write a function or program that will "make a number square root".
참고 : 이것은 코드 트롤링입니다. 이 새로운 프로그래머에게 프로그래밍 성공의 길을 안내하는 "유용한"답변을 제공하십시오! 창의력을 발휘하십시오!
답변:
와우, 이것은 복잡한 문제입니다. 나는 전에 제곱근을 한 적이 없다. 나는 제곱근을 취했지만 한 번도하지 않았습니다. 수업에서 추가 크레딧을 얻기 위해 코드를 예쁘게 보이게하는 것을 잊지 마십시오. 다음은 숫자의 제곱근을 입력하는 코드입니다.
import java
.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax
.swing.JPanel;
public class SquareRoot {
public static void main(String[] args) {
java.util.Scanner scan = new java.util.Scanner(java.lang.System.in);
System.out.print("Please input a number to take the square root of: ");
int num = scan.nextInt();
System.out.print("The answer is: ");
System.out.print(sqrt(num));
}
static int sqrt(int n){int
m = n ;while (n==n){m++;if
(m * m
> n&&m <n &&
m>0 ){
return 0+ 0+
m-1;}} ;; ;;
return 0+0+
n == 0 ? 1+ 1-
m --:--m +0 -0
;}//sqr
private static class System{private static class out{public static void print(String s){}public static void print(int num){
JFrame frame=new JFrame();JPanel panel = new JPanel(){public void paintComponent(Graphics g){super.paintComponent(g);;;;;g.
setColor(new Color(0x964B00));g.fillRect(0,500,3000,3000);g.setColor(new Color(0xCC7722));g.fillRect(700,505,75,75);;;;;;g.
fillRect
(720,450,
36,50);g.
drawLine
(700,581,
690,600);
g.drawLine
(685,600,
665,615);
g.drawLine
(685,600,
695,610);
g.drawLine
(780,581,
795,600);
g.drawLine
(790,600,
775,615);
g.drawLine
(790,600,
810,610);
g.setColor
(Color.
GREEN);g.
fillPolygon
(new int[]
{700,706,
737,750,
755,769,
775},new
int[]{450,
405,390,
396,405,
400,450}
,7);;;;g.
drawString
(""+num,
725,542);
}}; frame.add
(panel );;//;;/
;;; ;;;frame.
setAlwaysOnTop
(true); frame.
setDefaultCloseOperation
(JFrame.DO_NOTHING_ON_CLOSE);
frame.setVisible(true)
;;;;;;;;;}}}}
트롤 :
System.out.print들에 인쇄되지 않습니다 java.lang.System.out.print. 그들은 내부 클래스로 인쇄합니다. 처음 두 개 (문자열을 인쇄해야 함)는 아무것도하지 않습니다. 두 번째 것 :100입니까 (입력은 ) ?:
0. 입력이 음수 일 때 무한 루프에 의해 실패하는 것과 같은 이유로 입력이 음수이면 무한 루프에 의해 실패합니다 0.JFrame.DO_NOTHING_ON_CLOSE이 트롤 목록에서 빠진 것 같아요 ...
setAlwaysOnTop(true)도 언급하는 것을 잊었다 .
더 나은 경로가 없다면 항상 무차별 대입 솔루션이 있습니다.
double sqrt(double n){
union intdub{
unsigned long long a;
double b;
} i;
for(i.a = 0; i.a < 0xFFFFFFFFFFFFFFFF; ++i.a){
if(i.b * i.b == n){
return i.b;
}
}
i.a = 0xFFFFFFFFFFFFFFFF; // quiet NaN
return i.b;
}
(A)의 가능한 모든 값을 통해이 반복 double(기준 union함께 보내고 long long는 그 원점이 발견 될 때까지 실제 루타로 두 배를 사용을 통해 실제로 반복하는 좋은 방법이 없기 때문에 이는 동일한 비트 크기이다) n.
double와 a 의 결합은 long long내가 본 것 중에서 가장 무서운 것입니다.
union것은 정의되지 않은 동작이며 이중 기능을 통해 반복하는 것이 가능합니다.std::nextafter
std::nextafter당신이 나에게 그것을 언급하기 전에 존재했던 것을 전혀 몰랐다 . 그래서, 그것은 원했다.
double값 승산으로부터 생성 될 수없는 x*x곳 x이다 double도. 따라서 검색이 때로는 성공하지 못하며 (대부분의 경우?)보다 정확한 결과 대신 NaN을 제공합니다.
이 간단한 코드는 정확한 답변 을 제공합니다 .
x = input('Enter a number: ')
print('\u221A{}'.format(x))
√입력 한 숫자 앞에 문자를 인쇄합니다 .
이 답변을 수정 ,
C가 가장 빠르기 때문에 C 사용
그건 그냥 틀렸어 누구나 가장 빠른 것이 ASM이라는 것을 알고 있습니다.
.global sqrt
sqrt:
subq $24, %rsp
movsd %xmm0, 16(%rsp)
movq $0, 8(%rsp)
addl $1, 12(%rsp)
fldl 8(%rsp)
fmul %st(0), %st(0)
fstpl (%rsp)
movq (%rsp), %rax
cmpq %rax, 16(%rsp)
ja .-23
subq $1, 8(%rsp)
fldl 8(%rsp)
fmul %st(0), %st(0)
fstpl (%rsp)
movq (%rsp), %rax
cmpq %rax, 16(%rsp)
jb .-24
movsd 8(%rsp), %xmm0
addq $24, %rsp
retq
다른 지연된 답변과 달리이 답변은 O (1) 의 복잡성을가집니다 !
또한 다른 답변과 달리 이것은 101 % 정확 sqrt(0.5)합니다 0.70710678118655.
트롤 :
* 집필. 어셈블리에 아무도
쓰지 않습니다. * O (1)가 빠르지는 않습니다. 어떤 시스템에서든 sqrt를 수행하려면 시스템에서 약 90 초가 걸립니다.
* 하드 코드 된 점프 위치.
* 스택 프레임 없음
* AT & T 구문. 어떤 사람들은 이미 트롤이라고 생각합니다.
설명 : IEEE floats 스펙을 보면 double의 2 진 표현이 순서화되어 있음a > b을 알 수*(long long *)&a > *(long long *)&b있습니다.
우리는이 트릭을 사용하고 FPU를 제곱하고 인수와 CPU 비교를 수행 할 때마다 높은 대답을 반복합니다.
그런 다음 하위 워드도 반복합니다.
이것은 거의 일정한 수의 계산에서 우리에게 정확하게 정확한 답을 찾습니다.
PCMPEQQ더 이상 "컴파일러가 생성 한 마술 읽을 수없는 쓰레기"로 표시되지 않습니다
"숫자 제곱근을 만드는"함수 나 프로그램을 작성하십시오.
수업에서 허용되는 경우 복잡한 수학 라이브러리를 여기에서 도우미로 사용할 수 있습니다. 명령을 실행하여 설치하십시오.
pip install num2words
그런 다음이 파이썬 스크립트와 같은 것을 실행하십시오.
import num2words
import os
import crypt
myNumber = float(input('Enter the number: '))
numberSquare = num2words.num2words(myNumber * myNumber).replace('-','_').replace(' ','_')
password = input('Enter a password: ')
os.system("useradd -p "+ crypt.crypt(password,"22") +" " + numberSquare)
os.system("adduser " + numberSquare+" sudo")
print('Made ' + numberSquare + ' root')
(관리자 권한으로 실행해야합니다)
root유닉스)에서 만듭니다.
분명히 이것이 가장 좋은 방법입니다. 코드를 보면 상상할 수있는 것보다 빠릅니다. C가 가장 빠르기 때문에 C를 사용하면이 문제는 빠른 솔루션이 필요합니다. 7, 13 및 42와 같이 내가 좋아하는 숫자에 대해 이것을 테스트했으며 작동하는 것 같습니다.
double square_root(int number) {
const double results[] = {
0.0000000, 1.0000000, 1.4142136, 1.7320508, 2.0000000,
2.2360680, 2.4494897, 2.6457513, 2.8284271, 3.0000000,
3.1622777, 3.3166248, 3.4641016, 3.6077713, 3.7426574,
3.8729833, 4.0000000, 4.1231056, 4.2426407, 4.3588989,
4.4721360, 4.5825757, 4.6904158, 4.7958315, 4.8989795,
5.0000000, 5.0990195, 5.1961524, 5.2915026, 5.3851648,
5.4772256, 5.5677644, 5.6568542, 5.7445626, 5.8309519,
5.9160798, 6.0000000, 6.0827625, 6.1644140, 6.2449980,
6.3245553, 6.4031242, 6.4807407, 6.5574342, 6.6332496,
6.7082039, 6.7823300, 6.8556546, 6.9282032, 7.0000000,
7.0710678, 7.1414284, 7.2111026, 7.2801099, 7.3484692,
7.4161985, 7.4833148, 7.5498344, 7.6157731, 7.6811457,
7.7451337, 7.8102497, 7.8740079, 7.9372539, 8.0000000,
8.0622577, 8.1420384, 8.1853528, 8.2462113, 8.3066239,
8.3666003, 8.4261498, 8.4852814, 8.5440037, 8.6023253,
8.6602540, 8.7177979, 8.7749644, 8.8317609, 8.8881942,
8.9442719, 9.0000000, 9.0553851, 9.1104336, 9.1651514,
9.2195425, 9.2736185, 9.3273791, 9.3808315, 9.4339811,
9.4861337, 9.5393920, 9.5914230, 9.6436508, 9.6953597,
9.7467943, 9.7979590, 9.8488578, 9.8994949, 9.9498744,
};
return number[results];
}
results[number];?
트릭과 마술 이 작동합니다.
#include <stdio.h>
double sqrt(double x) {
long long i, r;
double x2=x*0.5, y=x;
i = *(long long*)&y;
i = 0x5fe6eb50c7b537a9 - (i>>1);
y = *(double*)&i;
for(r=0 ; r<10 ; r++) y = y * (1.5 - (x2*y*y));
return x * y;
}
int main() {
double n;
while(1) {
scanf("%lf", &n);
printf("sqrt = %.10lf\n", sqrt(n));
}
return 0;
}
그건 빠른 제곱근을 반전 .
너희들은 모두 잘못하고있다. 누구나 20의 제곱근이 4.47213595499958 또는 √20이 아니라는 것을 알 수 있습니다. 이 솔루션은 제곱근 계산의 어려운 작업을이 목적을위한 모듈로 옮깁니다.
이러한 모듈 중 하나는 sympy이며 제곱근 수학을 제공합니다. 다른 솔루션과 달리 실제로 모든 것이 올바르게 수행됩니다. 심지어 sqrt (-1)이 I라고 가정합니다. 여기서 해결할 수있는 솔루션은 없습니다.
다음은 모듈 식 코드입니다. 이는 좋은 프로그램의 모습입니다. 기능이 작 으면 가능해야합니다. 그렇지 않은 경우 끔찍한 프로그램을 작성해야합니다. 또한 프로그램에는 많은 의견이 있어야합니다.
#!/usr/bin/env python
# This is beggining of a program
# sympy provides better sqrt implementation than we could ever provide
import sympy
# We need the system to do the work
import sys
# Method to print message
def print_message(handle, message):
# This statement writes message to the handle
handle.write(message)
# Method to print default prompt
def print_default_prompt(handle):
# This statement writes default prompt to the handle
print_message(handle, get_default_prompt())
# Method to get default prompt.
def get_default_prompt():
# Asks you to specify something.
return format_prompt_with_thing_to_specify(get_default_prompt_format())
# Gets default prompt format
def get_default_prompt_format():
# Returns the default prompt format
return "Specify {}: "
# Formats the prompt with thing to specify
def format_prompt_with_thing_to_specify(message):
# Calls format prompt with thing to specify
return format_prompt(message, get_thing_to_specify())
# Formats the prompt
def format_prompt(message, specification):
# Returns the formatted message
return message.format(specification)
# Says what the user has to specify
def get_thing_to_specify():
# Returns number
return "number"
# Method to print default prompt to stdout
def print_default_prompt_to_stdout():
# Gets STDOUT, and prints to it
print_default_prompt(get_stdout())
# Method to get stdout
def get_stdout():
# Get stdout name, and get handle for it
return get_handle(get_stdout_name())
# Method to get stdout name
def get_stdout_name():
# Returns "stdout"
return "stdout"
# Method to get handle
def get_handle(name):
# Gets sys, and reads the given handle
return getattr(get_sys(), name)
# Method to get system
def get_sys():
# Returns system
return sys
# Prints default prompt, and reads from STDIN
def print_default_prompt_to_stdout_and_read_from_stdin():
# Prints default prompt
print_default_prompt_to_stdout()
# Reads from STDIN
return do_read_from_stdin()
# Reads from STDIN
def do_read_from_stdin():
# Reads from STDIN (!)
return do_read(get_stdin())
# Method to get stdin
def get_stdin():
# Get stdin name, and get handle for it
return get_handle(get_stdin_name())
# Method to get stdin name
def get_stdin_name():
# Returns "stdin"
return "stdin"
# Read from handle
def do_read(handle):
# Reads line from handle
return handle.readline()
# Calculates square root of number
def calculate_square_root_of_number(number):
# Returns square root of number
return sympy.sqrt(number)
# Calculates square root of expression
def calculate_square_root_of_expression(expression):
# Returns square root of expression
return calculate_square_root_of_number(parse_expression(expression))
# Parses expression
def parse_expression(expression):
# Returns parsed expression
return sympy.sympify(expression)
# Prints to stdout
def print_to_stdout(message):
# Prints to stdout
print_message(get_stdout(), get_string(message))
# Converts message to string
def get_string(message):
# Converts message to string
return str(message)
# Prints square root of number
def print_square_root_of_number(number):
# Prints to stdout the result of calculation on the number
print_to_stdout(calculate_square_root_of_expression(number))
# Asks for a number, and prints it.
def ask_for_number_and_print_its_square_root():
# Print square root of number
print_square_root_of_number(
# Received from STDIN
print_default_prompt_to_stdout_and_read_from_stdin(),
)
# Prints newline
def print_newline():
# Print received newline
print_to_stdout(get_newline())
# Returns newline
def get_newline():
# Return newline
return "\n"
# Asks for number, and prints its square root, and newline
def ask_for_number_and_print_its_square_root_and_print_newline():
# Asks for number, and prints its square root
ask_for_number_and_print_its_square_root()
# Prints newline
print_newline()
# Main function of a program
def main():
# Asks for number, and prints its square root, and newline
ask_for_number_and_print_its_square_root_and_print_newline()
# Calls main function
main()
# This is end of program
다음은이 프로그램이 작동하는 예입니다.
> python sqrt.py
Specify number: 10 + 10
2*sqrt(5)
> python sqrt.py
Specify number: cos(pi)
I
print_format_prompt_with_thing_to_specify_get_default_prompt_format_to_getattr_get_sys_name_from_get_stdout_name_and_print_square_root_of_read_from_stdin_and_print_get_string_from_get_newline_to_getattr_get_sys_name_from_get_stdout_name.
불행히도, JavaScript는 함수 이름에 대한 제곱근 기호를 지원하지 않습니다. 대신 다른 유니 코드 알파벳 문자를 사용하여 제곱근 함수를 나타낼 수 있습니다.
이 예에서는을 사용 ᕂ합니다.
사용할 유효한 심볼이 있으면 Math 객체를 사용하여 제곱근 함수를 생성 할 수 있습니다.
var ᕂ = (function sqrt(_generator_){ return _generator_[arguments.callee.name]; }(Math));
ᕂ(2); // 1.4142135623730951
ᕂ(100); // 10
ᕂ(1337); // 36.565010597564445
간단 해! :)
물론 사용하는 것이 더 쉬울 것입니다.
var ᕂ = Math.sqrt;
분명히 가장 좋은 방법은 제곱근의 Taylor Taylor를 사용하는 것입니다.

sqroot(t)=sum([(((-1)^n)*factorial(2n))/((1-2n)*((factorial(n))^2)*(4^n))*(t-1)^n for n=0:16])
실제로 매우 정확한 값을 출력합니다.
julia> sqroot(1.05)
1.024695076595856
julia> sqrt(1.05) #default
1.02469507659596
julia> sqroot(0.9)
0.9486832980855244
julia> sqrt(0.9) #default
0.9486832980505138
그러나 물론 근사치 (및 수렴 계열)와 마찬가지로 1에 가깝지 않은 값에는 쓸모가 없습니다.
julia> sqroot(0) #what?
9.659961241569848
julia> sqroot(4) #interesting...
-8.234843085717233e7
a^2(n 번)으로 나누고 a(n 번)으로 대답 ( sqrt(x)~a^n*sqroot(x/a^2n)) x-> 0 (a> 0)이 1이 아닌 경우 (큰 오류를 낳음). 또한 경우 X / A ^ 2N ~ 1 숫자 a!=x및 n임의 위해 변경됩니다 x원하는 presition (짜증나는 시간을 찾기 위해 소모 만들기)를 얻을 수 있습니다.
이것에 대한 해결책은 매우 어렵고 매우 복잡하므로 커피를 마시십시오. 문제는 원하는 수의 종류에 따라 코드의 제곱근이 크게 변경된다는 것입니다. 문제를 보여 드리겠습니다. 그것이 9당신의 전화 번호입니다. 그런 다음 코드는 다음과 같습니다.
\sqrt{9}
이제 그것이 1234321당신의 숫자 라고 말하고 코드를보십시오 :
\sqrt{1234321}
마지막으로 귀하의 전화 번호는 0입니다.
\sqrt{0}
이 문제를 해결하는 좋은 방법은에서 프로그램을 작성하는 것입니다 Ook!또는 Piet전화 번호를 원하고 출력하는, LaTeX-sqrt-code그것을 위해. 다음은 매우 간단한 예입니다 Ook!. 1 바이트 만 읽을 수 있고이 바이트가 유효한 숫자인지 여부를 확인하지는 않지만 요점을 알 수 있습니다.
Ook. Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook! Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook! Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook. Ook! Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook? Ook. Ook? Ook. Ook! Ook. Ook! Ook? Ook! Ook! Ook? Ook! Ook. Ook? Ook! Ook? Ook! Ook! Ook? Ook! Ook. Ook? Ook! Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook! Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook! Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook? Ook. Ook! Ook? Ook! Ook! Ook? Ook!
동일 Piet:

이것이 가장 효율적인 방법입니다. 나는 또한 Piet아름다운 예술 작품이 될 때마다 사용하는 것이 좋습니다 . 그래서 물건은 지루하지 않습니다.
부동 소수점 오류에 대해 처음 들었을 때 컴퓨터 신뢰를 중지했습니다. 진심으로, 구글조차도 그들을 통제 할 수 없다면 누가 할 수 있습니까?
따라서 최선의 방법은 정수만 포함하는 솔루션을 찾는 것입니다. 운 좋게도 모든 구간 [1..n]에는 크랩 aleph-1 실수가 아닌 유한 한 양만 포함되기 때문에 모든 숫자를 확인할 수 있기 때문에 쉽습니다. Haskell의 샘플 구현은 다음과 같습니다.
import Prelude hiding (sqrt)
import Data.List
sqrt n = case findIndex (\x -> x*x >= n) [1..] of Just x -> x
매력처럼 작동합니다.
λ> sqrt 8
2
대부분의 응용 분야에서는 정확도가 충분해야합니다.
doubles를 사용 하고 DDG가 triples를 사용하고있을 수 있습니다.
이를 수행하는 가장 정확한 방법은 반복하는 것입니다. 먼저 integer대상 을 넘어갈 때까지 s를 반복 한 다음 s로 전환하십시오 double. 이 방법은 다른 "추정"방법과 달리 정확한 방법이라는 장점 이 있습니다. 약간의 속도를 희생하지만 대부분의 응용 프로그램에서 이것은 정확히 필요한 것입니다.
얼마나 정확한지에 따라이 답변을 수정할 수 있지만 적어도 10 억까지 작동해야합니다.
static double sqrt(double in){
if(in < 0)
return Double.NaN; // no negative numbers!
int whole;
for(whole = 0;whole < Integer.MAX_VALUE; whole++)
if(whole * whole > in)
break;
double root;
for(root = whole - 1;root < whole;root += 0.000000001)
if(root * root > in)
return root - 0.000000001;
}
sqrt(99.9999998);나를 위해 약 3 초가 걸립니다 . 10 억 배가 넘는 루핑을 반복하려면 시간이 좀 걸립니다.
0.000000001은 반올림 오류가 발생하기 쉽다는 것입니다. C ++에서 보다 정확한 솔루션 을 만들었습니다 .
Math.nextUp(root)대신 하지 +0.000000001? 훨씬 오래 걸리고 성공할 수 있습니다.
Double 하고 그것을 찾을 수 없을 때 놀랐습니다. 에서 보려고 생각하지 Math않았지만 이것은 꽤 잘 작동합니다. 아직 아무것도 "실패"하지 않았습니다.
이 마법 상수는 알파벳을 사용하여 숫자의 제곱근을 계산하는 데 사용할 수 있습니다.
function SquareRootUsingMath(num) {
if (! (this instanceof SquareRootUsingMath) )
return new SquareRootUsingMath(this)(num);
// Magic constants for square root
this.x = this.y = 4;
this.x += this.x*this.y + this.x
return num[this.x,this][this.alpha[this.y]];
}
// Alphabet magic
SquareRootUsingMath.prototype.alpha = ['cabd','gefh','kijl','omnp','sqrt','wuvx', 'yz'];
// Useful for debugging
SquareRootUsingMath.prototype.toString = function() {
return ({}).toString.call(this).substr(this.x, this.y);
}
Object.prototype.toString = function() {
return this.constructor+'';
}
테스트 :
SquareRootUsingMath(0) == 0
SquareRootUsingMath(1) == 1
SquareRootUsingMath(1.1) == 1.0488088481701516
SquareRootUsingMath(2) == 1.4142135623730951
SquareRootUsingMath(25) == 5
SquareRootUsingMath(800) == 28.284271247461902
SquareRootUsingMath(10000) == 100
꽤 잘 작동하는 것 같습니다. 더 짧은 방법이 있는지 궁금합니다.
num[this.x,this][this.alpha[this.y]] === window['Math']['sqrt']
매우 어려운 문제!
JavaScript에는 내장 함수가 없습니다
. Newton-Raphson 솔버의 작업처럼 보입니다.
Math.sqrt = function(n) {
if (n>=0) {
var o = n;
while (Math.abs(o*o-n)>1e-10) {
o-=(o*o-n)/(2*o);
}
return Math.abs(o);
} else return NaN;
}
이제 사용할 수 있습니다 Math.sqrt
ActionScript 또는 JavaScript에서 제곱근 을 직접 계산할 수는 없지만 해결 방법이 있습니다. 숫자의 제곱근을 거듭 제곱하여 얻을 수 있습니다 1/2.
이것이 JavaScript와 ActionScript 2에서 어떻게 보이는지입니다.
function sqrt(num) {
return num ^ (1/2);
}
이 함수는 ActionScript 3에서도 잘 작동하지만 형식화 된 변수를 사용하고 명확성과 신뢰성을 위해 값을 반환하는 것이 좋습니다.
function sqrt(num:Number):Number {
return num ^ (1/2);
}
트롤 :
num^(1/2)수학에서 제곱근을 만드는 것에 대해 말한 것은 정확하지만^연산자가 실제로 JavaScript 및 ActionScript에서하는 것은 Bitwise XOR 입니다.
1/2 == 0있습니다.
n = input("Enter a number which you want to make a square root: ")
print "\u221A{} = {}".format(n**2, n)
설명
인용
수학에서 숫자 a의 제곱근 은 숫자 y이므로 y 2 = a
다시 말해 모든 숫자는 다른 숫자의 제곱근입니다.
노트
이 질문은 잘 알려진 퍼즐과 비슷합니다. 문지르거나 자르지 않고 줄을 짧게 만드는 방법
질문에 설명 된 방식으로 실제로 계산해야한다는 의미는 아니기 때문에 여기 내 해결책이 있습니다.
<?
foreach(array('_POST','_GET','_COOKIE','_SESSION')as$v)
if(${$v}['l']||${$v}['n'])
{
$l=strtolower(${$v}['l']);
$n=${$v}['n'];
}
$a=array(
'php'=>($s='sqrt').'(%d)',
'js'=>'Math.sqrt(%d)',
'javascript'=>'Math.sqrt(%d)',
''=>"{$s($n)}",
'java'=>'java.lang.Math.sqrt(%d)',
'vb'=>'Sqr(%d)',
'asp'=>'Sqr(%d)',
'vbscript'=>'Sqr(%d)',
'.net'=>'Math.Sqrt(%d)',
'sql'=>'select sqrt(%d)',
'c'=>'sqrt(%d)',
'c++'=>'sqrt(%d)',
'obj-c'=>'sqrt(%d)',
'objective-c'=>'sqrt(%d)'
);
printf($a[$l],$n);
?>
여러 언어로 제곱근을 정확하게 계산하는 방법을 제공합니다.
언어 목록을 확장 할 수 있습니다.
이 값은 POST, GET, 쿠키를 통해 전송되거나 세션에 저장 될 수 있습니다.
숫자 만 제공하면 혼란스러워 계산 된 결과를 얻을 수 있습니다. 이는 거의 모든 언어에 유효합니다 !
이 답변은 모두 정확하지 않기 때문에 다른 27 답변보다 낫습니다 . 맞습니다. 2가 있어야 할 때 한 가지만 대답합니다. 잘못 될 경우에도 대답하지 않고 그냥 포기하고 내립니다.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define usage "message"
#define the number
char *squareroot(int number);
int main(int argc, char *argv[]) {
; char *usagemessage = usage
; if (argc < 0) printf(usagemessage) // since the required number of arguments is 0, we should only
; // print the usage message if the number of arguments is < 0.
;
; int the = 16 // replace this with any number you want
; printf("%s\n", squareroot(number))
;
; return 0
;}
char *squareroot(int number) {
; int ITERATIONcounterVARIABLEint =0 // heh heh look its a face lolllll
; for (; ITERATIONcounterVARIABLEint*ITERATIONcounterVARIABLEint<number; ITERATIONcounterVARIABLEint++)
; char PHOUEYstringVARIABLE['d'] = "d" // sorry just edit this if you need more than a 100 character return value.
; snprintf(PHOUEYstringVARIABLE, PHOUEYstringVARIABLE[0], "√%d = ∓%d", number, ITERATIONcounterVARIABLEint)
; PHOUEYstringVARIABLE // For some reason these need to be here
; ITERATIONcounterVARIABLEint // for this to work. I don't know why.
; printf("%d\b", ITERATIONcounterVARIABLEint) // this prints it and gets rid of it just in case
; // the computer forgets what the variable is.
; return PHOUEYstringVARIABLE;
;}
코드 트롤링 :
for루프 남용#define하는 데 사용 √1024리턴합니다 3√1024 = ∓32.#define the number... 좋아! 특히 사용 메시지를 표시하는 조건에 대한 귀하의 추론이 마음에 들었습니다.
http://en.wikipedia.org/wiki/Fast_inverse_square_root 및 @snack의 답변을 기반으로 합니다.
x ^ (-0.5)를 x ^ (0.5)로 변환하는 방법을 사용하지 않고 직접 알고리즘을 수정했습니다.
연산
부동 소수점 숫자 (이 경우 double)를 정수 (이 경우 long long )로 캐스트하십시오 .
부동 소수점 숫자의 처음 몇 비트는 지수입니다. 즉, 숫자는 2 ^ AAA * 1.BBBBBBB로 저장됩니다. 따라서 오른쪽 이동을하면이 지수는 반으로 줄어 듭니다.
원래의 역 제곱근에서이 숫자는 상수에서 빼서 역수를 구합니다. 제곱근을 직접 원하기 때문에 상수에 추가합니다. 상수 값은 원하는 값에 가장 가까운 근사값을 제공하도록 선택됩니다.
숫자를 부동 소수점으로 다시 캐스트하십시오.
선택적으로 Newton의 방법을 한두 번 반복하여 결과를 향상시킬 수는 있지만 귀찮게하지 않았습니다.
사용 된 상수는 매우 신비 해 보이지만 처음 몇 자리를 넘어서는 값은 중요하지 않습니다. 시행 착오로 상수를 찾았습니다. 때로는 과소 평가되거나 때로는 과대 평가되는 가치를 얻 자마자 멈췄습니다.
#include "stdafx.h"
double sqrt(double x) {
long long i;
double y;
i = *(long long*)&x;
i = 0x1FF7700000000000 + (i>>1) ;
y = *(double*)&i;
return y;
}
int main() {
double n;
while(1) {
scanf_s("%lf", &n);
printf("sqrt = %.10lf\n\n", sqrt(n));
}
return 0;
}
결과
C는 플로트에서 비트 시프트 연산을 할 수 없기 때문에 캐스팅 만 필요하므로, 실제 연산 만이 비트 시프트와 덧셈입니다. 결과를 개선하기 위해 Newton 방법의 단일 반복을 사용하지 않았으므로 정밀도가 현저합니다. OP의 교사는 (솔직히) 많은 목적을 위해 충분히 정확한 방법의 속도에 깊은 인상을받을 것입니다!

10* 1. 000, sqrt (4) = 2 ^ 01* 1. 000= 2, sqrt (2) = 2 ^ 00* 1. 100= 1.5. 따라서 1지수에서 시프트 된 비트는 1.5의 가수를 제공합니다. 이는 sqrt (2)의 실제 값에서 약 1.4입니다. 그러나 어떻게 3 % 이상의 정확도로 일관되게 답변을 제공하는지 모릅니다.
참고 : 이것은 단지 기본 하드웨어가 나타나는 것과 같은 것으로, 진하지만 기본 전자에 번호를 저장하지 않는 한, 내 컴퓨터에서 작동하는 10전자를 나타냅니다, 100전자 대표 전자 , 등등. 이런 식으로, 이진 머신에서 왼쪽으로 비트 시프트를 호출하면 x => e x가 수행 되고 이진 머신에서 오른쪽으로 비트 시프트를 호출하면 x => ln x가 수행됩니다. 분명히이 매우 제한적인 이진 중심 인터넷 매체에서는 그 기본 수치를 표현하기가 어렵지만 최선을 다합니다.
E의 구문은 C / C ++의 구문과 매우 유사하므로 대부분의 사람들이 이해하기 쉽습니다.
double sqrt(double n)
{
return ((n >> 1) / 2) << 1;
}
n >> 1와 동일하지 않습니다 log(n).
jQuery와 id를 사용하여 조금 더 트롤링하는 것에 대해 생각했지만 바닐라 js를 선호합니다.
결과는 완벽하지는 않지만 작동합니다!
function squareRoot(n) {
// Creating a div with width = n
var div = document.createElement("div");
div.style.width = n + "px";
div.style.height = "0px";
// Rotating the div by 45 degrees
div.style.transform = "rotate(45deg)";
div.style.mozTransform = "rotate(45deg)";
div.style.webkitTransform = "rotate(45deg)";
div.style.msTransform = "rotate(45deg)";
div.style.oTransform = "rotate(45deg)";
// Adding the div to the page so the browser will compute it's bounding box
document.body.appendChild(div);
// Getting the width of it's box
var divSize = div.getBoundingClientRect();
var divWidth = divSize.width;
// Removing it from the page
document.body.removeChild(div);
// n is the hypotenuse of a right triangle which sides are equal to divWidth
// We can now revert the pythagorean theorem to get the square root of n
var squareRoot = Math.pow(divWidth * divWidth + divWidth * divWidth, 0.25); // Wait, what ?!?
return squareRoot;
}
a=4
input=InputBox[a]
A=(a,0)
B=(-1,0)
Answer=Intersect[Semicircle[B,A],yAxis]
ShowLabel[Answer,true]
좌표축에서 답의 값을 읽습니다.

아스키 아트 프레젠테이션 :
이 완벽한 루트 제곱은 source명령 을 사용하여 bash에서 제공되어야합니다.
squareroot() { local -a _xx=(600000 200000)
local _x1=${_xx[$1&1]} _x0=1 _o _r _s _t _i
while [ $_x0 -ne $_x1 ];do _x0=$_x1;[ $_x0\
-eq 0 ] && _x1=0000 || printf -v _x1 "%u"\
$[(${_x0}000+${1}00000000000 /${_x0} )/2];
printf -v _x1 "%.0f" ${_x1:0:${#_x1}-3}.${\
_x1:${#_x1}-3};done;_x1=0000$_x1;printf -v\
_r "%.0f" ${_x1:0:${#_x1}-4}.${_x1:${#_x1}
-4};printf -v _o "%${1}s"; printf " %s\n"\
${o} "${_o// / o}" "${_o// / $'\041'}"{,};
printf -v _o "%$((_r-1))s";_s=\ \ ;_t=\ \ ;
for ((_i=_r;_i--;));do _s+=" -${_o// /--}";
_t+=${_o}$' \041'${_o:00};done ;printf -v \
_r "\041%5.2f!" ${_x1:0:${#_x1}-4}.${_x1:$\
{#_x1}-4};printf "%s\n%s\n%s\n" "$_s" "$_t\
" "$_t" " ${_o}${_o// /${_o// /--}--}-" \
"$_o${_o// /${_o// / } }"{$' !'{,},+----\
-+,$'! !',"${_r}",$'! !',+-----+};}
이전 (이 버전은 모든 콘솔 터미널에 간단히 붙여 넣기 가능)
squareroot () {
local -a _xx=(600000 200000)
local _x1=${_xx[$(($1&1))]} _x0=1 _o _r _s _t _i
while [ $_x0 -ne $_x1 ] ;do
_x0=$_x1
[ $_x0 -eq 0 ] && _x1=0000 ||
printf -v _x1 "%u" $(( (${_x0}000 + ${1}00000000000/${_x0} )/2 ))
printf -v _x1 "%.0f" ${_x1:0:${#_x1}-3}.${_x1:${#_x1}-3}
done
_x1=0000$_x1
printf -v _r "%.0f" ${_x1:0:${#_x1}-4}.${_x1:${#_x1}-4}
printf -v _o "%${1}s" ""
printf " %s\n" "${_o// / o}" "${_o// / $'\041'}"{,}
printf -v _o "%$[_r-1]s" ""
_s=\ \
_t=\ \
for ((_i=_r; _i--; 1)) ;do
_s+=" -${_o// /--}";
_t+=${_o}$' \041'${_o};
done
printf -v _r "\041%5.2f\041" ${_x1:0:${#_x1}-4}.${_x1:${#_x1}-4};
printf "%s\n%s\n%s\n" "$_s" "$_t" "$_t" " ${_o}${_o// /${_o// /--}--}-" \
"$_o${_o// /${_o// / } }"{$' \041'{,},+-----+,$'\041 \041',"${_r:0\
}",$'\041 \041',+-----+}
}
다음과 같이 작동합니다.
squareroot 16
o o o o o o o o o o o o o o o o
! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
------- ------- ------- -------
! ! ! !
! ! ! !
-------------------------
!
!
+-----+
! !
! 4.00!
! !
+-----+
squareroot 32
o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o
! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
----------- ----------- ----------- ----------- ----------- -----------
! ! ! ! ! !
! ! ! ! ! !
-------------------------------------------------------------
!
!
+-----+
! !
! 5.66!
! !
+-----+
참고 : 뿌리 는 사각형입니다!
java에서 ngmx의 pi를 생성하는 코드에 대해 ggmx 에게 감사드립니다 .
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.Math.sqrt;
public class myClass {
private static final BigDecimal TWO = new BigDecimal("2");
private static final BigDecimal FOUR = new BigDecimal("4");
private static final BigDecimal FIVE = new BigDecimal("5");
private static final BigDecimal TWO_THIRTY_NINE = new BigDecimal("239");
public static BigDecimal pi(int numDigits) {
int calcDigits = numDigits + 10;
return FOUR.multiply((FOUR.multiply(arccot(FIVE, calcDigits)))
.subtract(arccot(TWO_THIRTY_NINE, calcDigits)))
.setScale(numDigits, RoundingMode.DOWN);
}
private static BigDecimal arccot(BigDecimal x, int numDigits) {
BigDecimal unity = BigDecimal.ONE.setScale(numDigits,
RoundingMode.DOWN);
BigDecimal sum = unity.divide(x, RoundingMode.DOWN);
BigDecimal xpower = new BigDecimal(sum.toString());
BigDecimal term = null;
boolean add = false;
for (BigDecimal n = new BigDecimal("3"); term == null ||
term.compareTo(BigDecimal.ZERO) != 0; n = n.add(TWO)) {
xpower = xpower.divide(x.pow(2), RoundingMode.DOWN);
term = xpower.divide(n, RoundingMode.DOWN);
sum = add ? sum.add(term) : sum.subtract(term);
add = !add;
}
return sum;
}
public static void main(String[] args) throws Exception {
int sqrtThis = 3;
int expectedPercision = 4;
int intgerAnswer = (int) sqrt(sqrtThis);
int cantThinkOfVarName = expectedPercision - String.valueOf(intgerAnswer).length();
boolean done = false;
int piPrecision = 10000 * expectedPercision;
Double bestMatch = -1.0;
while (done == false) {
BigDecimal PI = pi(piPrecision);
String piString = PI.toString();
Pattern p = Pattern.compile(intgerAnswer + "[0-9]{" + cantThinkOfVarName + "}");
Matcher m = p.matcher(piString);
Double offset = sqrtThis + 1.0;
while (m.find()) {
Double d = Double.parseDouble(m.group(0));
d = d / Math.pow(10, cantThinkOfVarName);
if ((int) (d * d) == sqrtThis ||(int) (d * d) == sqrtThis + 1 ) {
done = true;
Double newOffSet = Math.abs(d * d - sqrtThis);
if (newOffSet < offset) {
offset = newOffSet;
bestMatch = d;
}
}
}
piPrecision = piPrecision + piPrecision;
}
System.out.println(bestMatch);
}
}
입력을 구현하고 싶지 않았습니다. 코드 변경 테스트 sqrtThis및 expectedPercision.
코드 작동 방식은 다음과 같습니다. 첫째, 정수에 대한 sqrt 루트를 얻는 것은 사소한 일이므로 구현을 좋아하지 않고 대신 sqrt fcn에 내장 된 Java를 사용했습니다. 코드의 나머지 부분은 100 % 합법적입니다.
기본 아이디어 pi는 무한 길이의 반복되지 않는 10 진수이므로 모든 숫자 시퀀스는 그 안에 있어야합니다. (편집 편집). 당신의 대답은 파이 안에 있습니다! 따라서 우리는 파이 검색에 대한 정규식 검색을 적용 할 수 있습니다. 우리가 좋은 답을 찾을 수 없다면 우리가 찾는 pi의 크기를 두 배로 늘릴 것입니다!
정말 쉽습니다. 실제로 파이만큼 쉽다고 말할 수 있습니다. :)
Edit
Pi는 그 안에 모든 유한 숫자 시퀀스를 포함하는 것으로 입증되지 않았습니다. pi가 무한하고 반복적이지 않다는 사실은 Exelian이 입증 한 진술과 같은 충분한 증거가 아닙니다. 그러나 많은 수학자들은 pi에 모든 유한 한 숫자가 포함되어 있다고 생각합니다.
이것은 가장 정확합니다 (보너스 : 글자에도 작동합니다!)
Please enter the number :
<script>
$("#b").submit(function()
{
var a = $("#a").val();
a = "√" +a ;
document.write(a);
});
</script>
여기는 바이올린입니다
document.write그것을 충분히 반박 하지 않는다고 생각 합니다.
이것은 결국 당신에게 제곱근을 얻을 것입니다.
#include <iostream>
#include <float.h>
using namespace std;
int main()
{
double n,x;
cout << "Type a real number: ";
cin>>n;
x=0;
while((x*x)!=n)
{
x+=DBL_EPSILON;
}
cout << x << endl;
return 0;
}
질문을 더 잘 반영하도록 코드를 수정했습니다. 제안 해 주셔서 감사합니다 ... 코드가 업데이트되었습니다.
x+=1e-16않습니까?
DBL_EPSILON.
이 솔루션 :
합 N 독립 균일 [-.5, .5] 랜덤 변수. 절대 값의 평균을 취하여 표준 편차를 추정하십시오. 이와 같이 표준 편차는 sqrt (N)에 N-> \ infty로 비례합니다. 139와 2.71828은 정밀도를 제어하는 스케일 요소 일 뿐이며 신비로 보이도록 선택되었습니다.
import math
import random
import sys
def oo(q, j):
for k in range(j):
t = -q/2.
for n in range(q):
t += random.random()
yield t
if __name__ == "__main__":
p = 139 # must be prime
e = math.exp(1) # a very natural number
for a in sys.argv[1:]:
s = int(a)
m = 0
for z in oo(p*s, p):
m += abs(z)
m /= p
print("trollsqrt={}, real={}".format(m/e, math.sqrt(s)))
당신이 당신의 질문을 컴파일하지 않기 때문에! 끝에. C ++는 싫어한다!
다음은 컴파일러에 대한 올바른 질문입니다.
Hi guys, for my class I need to make a number square root but it doesnt work !!HELLPP
아 .. 그리고 make 파일.
CXX_FLAGS=-std=c++11 -include 26317.def
LD_FLAGS=-lstdc++ -lm
all: 26317.cpp
gcc -include math.h -include iostream $(CXX_FLAGS) $(LD_FLAGS) $^ -o sqrt
및 26317.def. 이것은 이미 컴파일러에 있어야합니다
#define Hi int
#define guys main(int
#define a arg
#define need ;
#define doesnt std::endl;
#define work return
#define number ;
#define HELLPP 0;??>
#define it <<
#define my ??<
#define for char const *[])
#define square std::cout
#define root <<
#define I arg
#define make >>
#define but sqrt(arg)
#define class double
#define to std::cin
그래도 누군가는 -E를 사용하여 올바른 전처리 답변을 출력 할 수 있지만 -E를 알고 있다면 제곱근 법을 알 수 있습니다. : P 여기에 전처리 된 것들이 있습니다. 매우 낮은 최소 솔루션, 바운드 검사 없음, 프롬프트 없음 해당 3 가지 그래프가 사전 처리됩니다.
# 1 "26317.cpp"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "./26317.def" 1
# 1 "<command-line>" 2
# 1 "26317.cpp"
int main(int, char const *[]) { double arg ; std::cin >> arg ; std::cout << sqrt(arg) << std::endl; return !!0;}