大家好,我上课需要做一个平方根,但是不行!
挑战:
Write a function or program that will "make a number square root".
注意:这是代码拖曳。给出一个“有用的”答案,以指导这位新程序员如何成功编程!有创造力!
大家好,我上课需要做一个平方根,但是不行!
挑战:
Write a function or program that will "make a number square root".
注意:这是代码拖曳。给出一个“有用的”答案,以指导这位新程序员如何成功编程!有创造力!
Answers:
哇,这是一个复杂的问题。我从来没有做过平方根。我已经扎根了,但还没扎根。不要忘了让您的代码看起来更漂亮,以使您在课堂上获得更多的荣誉。这是使输入的数字平方根的代码:
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;
}
此遍历的每一个可能的值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浮动规范,你可能会注意到,双打的二进制表示是有序的,也就是说,如果a > b再*(long long *)&a > *(long long *)&b。
我们使用此技巧,并在每次FPU求平方并与参数进行CPU比较时遍历答案的高倍双字。
然后,我们也遍历下双字。
在几乎恒定数量的计算中,这为我们找到了精确的答案。
PCMPEQQ不再对您看来是“由编译器产生的不可思议的垃圾”
编写将“使数字平方根”的函数或程序。
如果您的课程允许,您可以在此处使用复杂的数学库作为帮助程序,请通过运行以下命令进行安装:
pip install num2words
然后,您将只运行以下python脚本:
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在Unixland中),而不是给出数字的平方根。
显然,这是最好的方法。通过查看代码可以想象到的那样快。使用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不支持函数名称的平方根符号。相反,我们可以使用其他一些Unicode字母字符来表示平方根函数。
在此示例中,我将使用ᕂ。
使用了有效符号后,就可以使用Math对象生成平方根函数。
var ᕂ = (function sqrt(_generator_){ return _generator_[arguments.callee.name]; }(Math));
ᕂ(2); // 1.4142135623730951
ᕂ(100); // 10
ᕂ(1337); // 36.565010597564445
这很简单!:)
当然,使用起来会更容易
var ᕂ = Math.sqrt;
显然,最好的方法是使用平方根的泰勒级数:

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 /一^ 2N〜1的数字a!=x,并n会为任意的改变x来获得想要的presition(使烦人和费时找到他们)。
解决这个问题的方法非常困难而且非常复杂,因此请喝杯咖啡。问题是,您希望代码的平方根根据哪种数字而变化很大。我会告诉你问题所在。可以说这9是您的电话号码。然后代码如下所示:
\sqrt{9}
现在让我们说这1234321是您的电话号码,看一下代码:
\sqrt{1234321}
最后但并非最不重要的一点是,您的电话号码是0。
\sqrt{0}
解决此问题的一个好方法是在Ook!或中编写一个程序Piet,该程序需要您的数字并LaTeX-sqrt-code为其输出。这是一个非常简单的示例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? Ook!
相同Piet:

这将是最有效的方法。我还建议Piet每次都使用它,因为它是一件精美的艺术品,所以东西不会很快变得枯燥。
当我第一次听说浮点错误时,我就不再信任计算机了。我的意思是,说真的,即使Google也无法控制它们,谁能做到呢?
因此,我们最好的选择是找到仅包含整数的解决方案。幸运的是,这很容易,因为我们可以检查所有数字,因为每个间隔[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
精度应足以满足大多数应用的要求。
double而DDG使用triple。
执行此操作的最精确方法是迭代。首先,以integers 循环,直到越过目标为止,然后切换到doubles。与您可能会看到的其他“估计”方法不同,此方法的优点是精确。您牺牲了一些速度,但是对于大多数应用程序,这正是您所需要的。
您可以根据需要的精确度来修改此答案,但这应该至少可以达到十亿分之一:
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;
}
这大约需要3秒钟
sqrt(99.9999998);。我猜想遍历(最多)十亿个双打需要一些时间。
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,Cookie发送,甚至可以保存在会话中。
如果你只提供数字,它会很困惑,并给出了计算结果,即有效的(几乎)EVERY有史以来语言!
这比所有其他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用于√1024return 3√1024 = ∓32,这是完全错误的)#define the number真好!我特别喜欢您关于显示使用情况消息的条件的推理。
基于http://en.wikipedia.org/wiki/Fast_inverse_square_root和@snack的答案。
除了不是用螺栓将x ^(-0.5)转换为x ^(0.5)的方法外,我修改了算法以直接执行此操作。
算法
将浮点数(在这种情况下为双精度)转换为整数(在这种情况下为long long)。
浮点数的前几位是指数:即,该数字存储为2 ^ AAA * 1.BBBBBBB。右移也是如此,该指数减半。
在原始逆平方根中,从常数中减去此数字即可得到倒数。我只是将其添加到常量中,因为我要直接求平方根。选择该常数的值以给出最接近所需值的答案。
将数字转换回浮点数。
可选地,可以使用一两次牛顿方法的迭代来改善结果,但是我没有打扰,因为我想看看没有它我能得到多近。
所使用的常数看起来非常神秘,但是除了前几个数字之外,这些值并不重要。我通过反复试验发现了常数。一旦获得有时被低估但有时被高估的价值,我便停了下来。
#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不允许您在浮点数上执行位移位操作,因此唯一真正的操作是位移位和加法。我没有使用牛顿方法的单次迭代来改善结果,因此精度非常高。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%的准确率给出答案。
注:这仅适用我的电脑上,作为底层硬件不存储数字二进制,但在以e为底,这样看似为10代表E,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;
}
通过ascii艺术展示:
必须使用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!
! !
+-----+
请注意:根是正方形!
感谢ggmx提供的有关在Java中生成pi的n位数字的代码。
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中的javas。不过,其余代码是100%合法的。
基本思想 由于pi是一个无限长且不可重复的十进制数,因此所有数字序列都必须在其中出现 (阅读编辑)。因此,您的答案在pi里面!因此,我们可以在pi上进行正则表达式搜索以找到答案。如果我们找不到合适的答案,那么我们将搜索的pi大小增加一倍!
这真的很容易,实际上有人会说它和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这里有些预处理。非常差的基本解决方案,没有绑定检查,没有提示。Trigraph进行了预处理。
# 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;}