Convert a double to a string containing rational and surd
$begingroup$
First off, code:
string FracSurd(double value)
{
//A C# 7 local function
double GCD(double a, double b)
{
while (b > 0)
{
var rem = a % b;
a = b;
b = rem;
}
return a;
}
for (int i = 0; i <= 1e6; i++)
{
var SubjectToTest = value / Math.Sqrt(i);
for (var denom = 1.0; denom <= 500; denom++)
{
var numer = Math.Round(SubjectToTest * denom);
if (SubjectToTest - numer / denom == 0)
{
int Square = 1, a = i;
for (int b = 2; a > 1; b++)
if (a % b == 0)
{
int x = 0;
while (a % b == 0)
{
a /= b;
x++;
}
//Console.WriteLine("{0} is a prime factor {1} times!", b, x);
for (int j = 2; j <= x; j += 2) Square *= b;
}
var LCM = GCD(numer, denom);
numer /= LCM;
denom /= LCM;
var Builder = new System.Text.StringBuilder(numer.ToString());
Builder.Append(" / ").Append(denom).Append(" √");
foreach (var Char in (i / Square).ToString())
{
#if WINDOWS_UWP
Builder.Append("̅");
Builder.Append(Char);
#else
Builder.Append(Char);
Builder.Append("̅");
#endif
}
return Builder.ToString();
}
}
}
throw new ArithmeticException("Cannot find appropiate fraction and surd.");
}
The code contains a lot of loops. How can I increase its performance so I can expand its range of input?
c# performance .net mathematics
$endgroup$
add a comment |
$begingroup$
First off, code:
string FracSurd(double value)
{
//A C# 7 local function
double GCD(double a, double b)
{
while (b > 0)
{
var rem = a % b;
a = b;
b = rem;
}
return a;
}
for (int i = 0; i <= 1e6; i++)
{
var SubjectToTest = value / Math.Sqrt(i);
for (var denom = 1.0; denom <= 500; denom++)
{
var numer = Math.Round(SubjectToTest * denom);
if (SubjectToTest - numer / denom == 0)
{
int Square = 1, a = i;
for (int b = 2; a > 1; b++)
if (a % b == 0)
{
int x = 0;
while (a % b == 0)
{
a /= b;
x++;
}
//Console.WriteLine("{0} is a prime factor {1} times!", b, x);
for (int j = 2; j <= x; j += 2) Square *= b;
}
var LCM = GCD(numer, denom);
numer /= LCM;
denom /= LCM;
var Builder = new System.Text.StringBuilder(numer.ToString());
Builder.Append(" / ").Append(denom).Append(" √");
foreach (var Char in (i / Square).ToString())
{
#if WINDOWS_UWP
Builder.Append("̅");
Builder.Append(Char);
#else
Builder.Append(Char);
Builder.Append("̅");
#endif
}
return Builder.ToString();
}
}
}
throw new ArithmeticException("Cannot find appropiate fraction and surd.");
}
The code contains a lot of loops. How can I increase its performance so I can expand its range of input?
c# performance .net mathematics
$endgroup$
$begingroup$
Is this real code? When did C# start supported nested functions?
$endgroup$
– Cody Gray
May 7 '17 at 10:24
3
$begingroup$
Check out C# 7's local functions :) Btw it's released with VS2017 so you may not be able to compile it in older VSs.
$endgroup$
– Happypig375
May 7 '17 at 11:08
3
$begingroup$
@CodyGray not up-to-date? ;-) You can also run it with the latest LINQPad.
$endgroup$
– t3chb0t
May 7 '17 at 11:37
add a comment |
$begingroup$
First off, code:
string FracSurd(double value)
{
//A C# 7 local function
double GCD(double a, double b)
{
while (b > 0)
{
var rem = a % b;
a = b;
b = rem;
}
return a;
}
for (int i = 0; i <= 1e6; i++)
{
var SubjectToTest = value / Math.Sqrt(i);
for (var denom = 1.0; denom <= 500; denom++)
{
var numer = Math.Round(SubjectToTest * denom);
if (SubjectToTest - numer / denom == 0)
{
int Square = 1, a = i;
for (int b = 2; a > 1; b++)
if (a % b == 0)
{
int x = 0;
while (a % b == 0)
{
a /= b;
x++;
}
//Console.WriteLine("{0} is a prime factor {1} times!", b, x);
for (int j = 2; j <= x; j += 2) Square *= b;
}
var LCM = GCD(numer, denom);
numer /= LCM;
denom /= LCM;
var Builder = new System.Text.StringBuilder(numer.ToString());
Builder.Append(" / ").Append(denom).Append(" √");
foreach (var Char in (i / Square).ToString())
{
#if WINDOWS_UWP
Builder.Append("̅");
Builder.Append(Char);
#else
Builder.Append(Char);
Builder.Append("̅");
#endif
}
return Builder.ToString();
}
}
}
throw new ArithmeticException("Cannot find appropiate fraction and surd.");
}
The code contains a lot of loops. How can I increase its performance so I can expand its range of input?
c# performance .net mathematics
$endgroup$
First off, code:
string FracSurd(double value)
{
//A C# 7 local function
double GCD(double a, double b)
{
while (b > 0)
{
var rem = a % b;
a = b;
b = rem;
}
return a;
}
for (int i = 0; i <= 1e6; i++)
{
var SubjectToTest = value / Math.Sqrt(i);
for (var denom = 1.0; denom <= 500; denom++)
{
var numer = Math.Round(SubjectToTest * denom);
if (SubjectToTest - numer / denom == 0)
{
int Square = 1, a = i;
for (int b = 2; a > 1; b++)
if (a % b == 0)
{
int x = 0;
while (a % b == 0)
{
a /= b;
x++;
}
//Console.WriteLine("{0} is a prime factor {1} times!", b, x);
for (int j = 2; j <= x; j += 2) Square *= b;
}
var LCM = GCD(numer, denom);
numer /= LCM;
denom /= LCM;
var Builder = new System.Text.StringBuilder(numer.ToString());
Builder.Append(" / ").Append(denom).Append(" √");
foreach (var Char in (i / Square).ToString())
{
#if WINDOWS_UWP
Builder.Append("̅");
Builder.Append(Char);
#else
Builder.Append(Char);
Builder.Append("̅");
#endif
}
return Builder.ToString();
}
}
}
throw new ArithmeticException("Cannot find appropiate fraction and surd.");
}
The code contains a lot of loops. How can I increase its performance so I can expand its range of input?
c# performance .net mathematics
c# performance .net mathematics
edited May 7 '17 at 11:35
Happypig375
asked May 7 '17 at 7:21
Happypig375Happypig375
1164
1164
$begingroup$
Is this real code? When did C# start supported nested functions?
$endgroup$
– Cody Gray
May 7 '17 at 10:24
3
$begingroup$
Check out C# 7's local functions :) Btw it's released with VS2017 so you may not be able to compile it in older VSs.
$endgroup$
– Happypig375
May 7 '17 at 11:08
3
$begingroup$
@CodyGray not up-to-date? ;-) You can also run it with the latest LINQPad.
$endgroup$
– t3chb0t
May 7 '17 at 11:37
add a comment |
$begingroup$
Is this real code? When did C# start supported nested functions?
$endgroup$
– Cody Gray
May 7 '17 at 10:24
3
$begingroup$
Check out C# 7's local functions :) Btw it's released with VS2017 so you may not be able to compile it in older VSs.
$endgroup$
– Happypig375
May 7 '17 at 11:08
3
$begingroup$
@CodyGray not up-to-date? ;-) You can also run it with the latest LINQPad.
$endgroup$
– t3chb0t
May 7 '17 at 11:37
$begingroup$
Is this real code? When did C# start supported nested functions?
$endgroup$
– Cody Gray
May 7 '17 at 10:24
$begingroup$
Is this real code? When did C# start supported nested functions?
$endgroup$
– Cody Gray
May 7 '17 at 10:24
3
3
$begingroup$
Check out C# 7's local functions :) Btw it's released with VS2017 so you may not be able to compile it in older VSs.
$endgroup$
– Happypig375
May 7 '17 at 11:08
$begingroup$
Check out C# 7's local functions :) Btw it's released with VS2017 so you may not be able to compile it in older VSs.
$endgroup$
– Happypig375
May 7 '17 at 11:08
3
3
$begingroup$
@CodyGray not up-to-date? ;-) You can also run it with the latest LINQPad.
$endgroup$
– t3chb0t
May 7 '17 at 11:37
$begingroup$
@CodyGray not up-to-date? ;-) You can also run it with the latest LINQPad.
$endgroup$
– t3chb0t
May 7 '17 at 11:37
add a comment |
1 Answer
1
active
oldest
votes
$begingroup$
This is not a good question because the objective is unrealistic. The code (or problem statement) is also flawed since √1 is considered a surd, which - if I am not mistaken - is wrong. (A surd is an "irrational nth root of a positive integer (n > 1)", i.e. it has a non-recurring floating point representation.)
Here is why the objective needs sorting out
Reasonably performant algorithms exist to express floating point numbers as irrational numbers (all of which may be expressed as x / y * √1). Here's an example (E&OE):
static string Frac(double value)
{
const double compareTolerance = 1.0E-12;
bool isNegative = value < 0;
value = Math.Abs(value);
long numerator = 1L;
long denominator = 1L;
double fraction = (double)numerator / denominator;
while (Math.Abs(fraction - value) > compareTolerance)
{
if (fraction < value)
numerator++;
else
{
denominator++;
numerator = (long)(value * denominator);
}
fraction = (double)numerator / denominator;
}
return $"{numerator} / {denominator} = {fraction}, error = {value - fraction}";
}
Given Console.WriteLine(Frac(2.0 / 3 * Math.Pow(7, 1.0/3)));
One gets 1238109 / 970847 = 1.27528745518089, error = 7.04103442217274E-13
Any given floating point number can be represented as a rational - which is an approximation, the accuracy of which depends on the numeric types being used. It is possible to take any rational, multiply (or divide) by a surd and get another rational - all "only accurate to N significant digits". Every floating point therefore has many rational * surd
representations, so you need to specify how you want to limit the range of output possibilities.
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f162727%2fconvert-a-double-to-a-string-containing-rational-and-surd%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
This is not a good question because the objective is unrealistic. The code (or problem statement) is also flawed since √1 is considered a surd, which - if I am not mistaken - is wrong. (A surd is an "irrational nth root of a positive integer (n > 1)", i.e. it has a non-recurring floating point representation.)
Here is why the objective needs sorting out
Reasonably performant algorithms exist to express floating point numbers as irrational numbers (all of which may be expressed as x / y * √1). Here's an example (E&OE):
static string Frac(double value)
{
const double compareTolerance = 1.0E-12;
bool isNegative = value < 0;
value = Math.Abs(value);
long numerator = 1L;
long denominator = 1L;
double fraction = (double)numerator / denominator;
while (Math.Abs(fraction - value) > compareTolerance)
{
if (fraction < value)
numerator++;
else
{
denominator++;
numerator = (long)(value * denominator);
}
fraction = (double)numerator / denominator;
}
return $"{numerator} / {denominator} = {fraction}, error = {value - fraction}";
}
Given Console.WriteLine(Frac(2.0 / 3 * Math.Pow(7, 1.0/3)));
One gets 1238109 / 970847 = 1.27528745518089, error = 7.04103442217274E-13
Any given floating point number can be represented as a rational - which is an approximation, the accuracy of which depends on the numeric types being used. It is possible to take any rational, multiply (or divide) by a surd and get another rational - all "only accurate to N significant digits". Every floating point therefore has many rational * surd
representations, so you need to specify how you want to limit the range of output possibilities.
$endgroup$
add a comment |
$begingroup$
This is not a good question because the objective is unrealistic. The code (or problem statement) is also flawed since √1 is considered a surd, which - if I am not mistaken - is wrong. (A surd is an "irrational nth root of a positive integer (n > 1)", i.e. it has a non-recurring floating point representation.)
Here is why the objective needs sorting out
Reasonably performant algorithms exist to express floating point numbers as irrational numbers (all of which may be expressed as x / y * √1). Here's an example (E&OE):
static string Frac(double value)
{
const double compareTolerance = 1.0E-12;
bool isNegative = value < 0;
value = Math.Abs(value);
long numerator = 1L;
long denominator = 1L;
double fraction = (double)numerator / denominator;
while (Math.Abs(fraction - value) > compareTolerance)
{
if (fraction < value)
numerator++;
else
{
denominator++;
numerator = (long)(value * denominator);
}
fraction = (double)numerator / denominator;
}
return $"{numerator} / {denominator} = {fraction}, error = {value - fraction}";
}
Given Console.WriteLine(Frac(2.0 / 3 * Math.Pow(7, 1.0/3)));
One gets 1238109 / 970847 = 1.27528745518089, error = 7.04103442217274E-13
Any given floating point number can be represented as a rational - which is an approximation, the accuracy of which depends on the numeric types being used. It is possible to take any rational, multiply (or divide) by a surd and get another rational - all "only accurate to N significant digits". Every floating point therefore has many rational * surd
representations, so you need to specify how you want to limit the range of output possibilities.
$endgroup$
add a comment |
$begingroup$
This is not a good question because the objective is unrealistic. The code (or problem statement) is also flawed since √1 is considered a surd, which - if I am not mistaken - is wrong. (A surd is an "irrational nth root of a positive integer (n > 1)", i.e. it has a non-recurring floating point representation.)
Here is why the objective needs sorting out
Reasonably performant algorithms exist to express floating point numbers as irrational numbers (all of which may be expressed as x / y * √1). Here's an example (E&OE):
static string Frac(double value)
{
const double compareTolerance = 1.0E-12;
bool isNegative = value < 0;
value = Math.Abs(value);
long numerator = 1L;
long denominator = 1L;
double fraction = (double)numerator / denominator;
while (Math.Abs(fraction - value) > compareTolerance)
{
if (fraction < value)
numerator++;
else
{
denominator++;
numerator = (long)(value * denominator);
}
fraction = (double)numerator / denominator;
}
return $"{numerator} / {denominator} = {fraction}, error = {value - fraction}";
}
Given Console.WriteLine(Frac(2.0 / 3 * Math.Pow(7, 1.0/3)));
One gets 1238109 / 970847 = 1.27528745518089, error = 7.04103442217274E-13
Any given floating point number can be represented as a rational - which is an approximation, the accuracy of which depends on the numeric types being used. It is possible to take any rational, multiply (or divide) by a surd and get another rational - all "only accurate to N significant digits". Every floating point therefore has many rational * surd
representations, so you need to specify how you want to limit the range of output possibilities.
$endgroup$
This is not a good question because the objective is unrealistic. The code (or problem statement) is also flawed since √1 is considered a surd, which - if I am not mistaken - is wrong. (A surd is an "irrational nth root of a positive integer (n > 1)", i.e. it has a non-recurring floating point representation.)
Here is why the objective needs sorting out
Reasonably performant algorithms exist to express floating point numbers as irrational numbers (all of which may be expressed as x / y * √1). Here's an example (E&OE):
static string Frac(double value)
{
const double compareTolerance = 1.0E-12;
bool isNegative = value < 0;
value = Math.Abs(value);
long numerator = 1L;
long denominator = 1L;
double fraction = (double)numerator / denominator;
while (Math.Abs(fraction - value) > compareTolerance)
{
if (fraction < value)
numerator++;
else
{
denominator++;
numerator = (long)(value * denominator);
}
fraction = (double)numerator / denominator;
}
return $"{numerator} / {denominator} = {fraction}, error = {value - fraction}";
}
Given Console.WriteLine(Frac(2.0 / 3 * Math.Pow(7, 1.0/3)));
One gets 1238109 / 970847 = 1.27528745518089, error = 7.04103442217274E-13
Any given floating point number can be represented as a rational - which is an approximation, the accuracy of which depends on the numeric types being used. It is possible to take any rational, multiply (or divide) by a surd and get another rational - all "only accurate to N significant digits". Every floating point therefore has many rational * surd
representations, so you need to specify how you want to limit the range of output possibilities.
answered 26 mins ago
AlanKAlanK
312
312
add a comment |
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f162727%2fconvert-a-double-to-a-string-containing-rational-and-surd%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
$begingroup$
Is this real code? When did C# start supported nested functions?
$endgroup$
– Cody Gray
May 7 '17 at 10:24
3
$begingroup$
Check out C# 7's local functions :) Btw it's released with VS2017 so you may not be able to compile it in older VSs.
$endgroup$
– Happypig375
May 7 '17 at 11:08
3
$begingroup$
@CodyGray not up-to-date? ;-) You can also run it with the latest LINQPad.
$endgroup$
– t3chb0t
May 7 '17 at 11:37