Complex derivative of the function at the point - c#

I'm writing a method to find the derivative of a function at a point.
static void Main(string[] args)
{
double x = 1;
double dx = 0.000001;
double rate;
rate = (((f(x + dx) - f(x)) / dx));
}
static double f(double x)
{
return Math.Cos(x);
//return 20*x - 5*Math.Pow(x, 2)+8*Math.Pow(x, 5/4);
}
Derivative of simple functions (like sin(x)) is calculated correctly, but a complex function (like (20*x - 5*Math.Pow(x, 2)+8*Math.Pow(x, 5/4))) - not true.

It looks as though the issue is caused by your integer division
5 / 4 == 1
5.0 / 4.0 == 1.25

try modifying the term 5/4 to 5/4f.

Related

I can't imagine what the code should be to solve these kinds of problems

Given the limit of changing the value of variables, calculate the function according to the formula.
enter image description here
This function is a little more difficult to imagine, before that I made a regular function and I can not imagine the essence of complex functions.
class Program
{
static void Main(string[] args)
{
double x <= 1.4;
Console.WriteLine("Enter the value of x:");
double x = Convert.ToDouble(Console.ReadLine());
double result = Math.sqr(x)-(7 / x);
double result2 = a * Math.pow(3, x) + 7 * Math.Sqrt(x);
double result3 = Math.log10(x + 7);
Console.WriteLine("The result of the function is: ");
}
}
Probably you should create a method for this function like:
public double f(double x)
{
if (x < 0.7 || x > 2)
throw new ArgumentOutOfRangeException(...);
if (x < 1.4)
return ...
else if (x == 1.4)
return ...
else
return ...
}
And then you can call this method from your Main() method, where you can get the value of x from user input, as you already do, and call f(x) to calculate the result.
There is an issue though. Floating point numbers are represented only approximately. E.g. value 1.4 can be actually stored as 1.399999999998... or 1.40000000000013..., so x == 1.4 comparison is not really correct.
Usually floating point values are checked against some interval, something like Math.Abs(x - 1.4) < 1E-15.
Another option is to use decimal type (see Difference between decimal, float and double in .NET?)

C# midpoint round down option for decimal

Im working with an external payment system which uses a round down at exact midpoint, but round up if its anything more than that. I want to replicate the same in my application to match the value.
For example with two decimal point rounding, 150.415 is rounded to 150.41 and 150.4151 is rounded to 150.42. I am not entirely sure what this rounding mechanism is called.
To replicate the same behaviour in C#, I tried using Math.Round(amount, 2, MidpointRounding.AwayFromZero) and Math.Round(amount, 2, MidpointRounding.ToEven), but both rounds off the above number to 150.42
Trying to see what are my options here, including writing a custom function to do a similar rounding?
I think this is the logic that you need:
public static decimal DigitalRiverRounding(decimal value)
{
if (value < 0)
return Math.Floor(value * 100 + 0.5m) / 100m;
return Math.Ceiling(value * 100 - 0.5m) / 100m;
}
If you are certain no negative numbers are involved, you can of course remove the first two lines. I assumed for negative numbers the desired output is mirrored (-150.415 => -150.41, so they compensate appropriately).
Explanation assuming rounding with no decimals: as Ceiling converts 1.01 - 2.00 to 2, by doing -0.5 you are translating that into a logic that does 0.51 - 1.50 to 1, therefore 1.51 - 2.50 to 2, which is what you need.
In case you need to use this everywhere in your app, you may want to use an extension method instead, which needs a separate static helper class:
public static decimal ToDigitalRiverRounding(this decimal value)
{
if (value < 0)
return Math.Floor(value * 100 + 0.5m) / 100m;
return Math.Ceiling(value * 100 - 0.5m) / 100m;
}
#include <iostream>
#include <cmath>
using namespace std;
double roundN(double val, int len)
{
double result;
result = val * pow(10.0, len);
result = static_cast<double>(static_cast<int>(result + 0.5));
result = result * pow(10.0, -len);
return result;
}
int main() {
double a;
cout<<"enter number"<<endl;
cin>>a;
a=roundN(a,2);
std::cout << a;
return 0;
}

How to comparing two x significant doubles correctly [duplicate]

This question already has answers here:
Round a double to x significant figures
(17 answers)
Closed 4 years ago.
This is not a duplicate question. There is an answer posted in the question. Hope it can help.
There are two doubles with the same value with decimals.
(Sorry, this is not a good case. because it will return false sometimes, but I can't find the case. If you try this case, it may not have any problem. So don't waste time to test it.)
double a = 0.70448;
double b = 0.70441;
I want to compare them with only 4 decimals.
I have this helper function to round them down to 4 decimals first.
public static double RoundDown(this double value, int decimals)
{
var multiplier = Math.Pow(10, decimals);
return Math.Floor(value * multiplier) / multiplier;
}
And then I want to check if a is larger than b like this:
RoundDown(a, 4) > RoundDown(b, 4)
Sometimes, for some cases, it will return true even they look equal. I understand very well this is floating issue, so I would like to know if there any elegant solution to compare them.
Updates:
I have tried to multiply it and compare them in integer. However, for this solution, I need to handle double infinity and NAN.
private static CompareResult Compare(double a, double b, double decimals = 0)
{
var multiplier = Math.Pow(10, decimals);
var aInt = Convert.ToInt32(a * multiplier);
var bInt = Convert.ToInt32(b * multiplier);
return aInt > bInt ? CompareResult.Greater : aInt < bInt ? CompareResult.Less : CompareResult.Equal;
}
private enum CompareResult
{
Greater,
Less,
Equal
}
System.OverflowException is thrown if one of the double is larger than int max or infinity. Also, this is not an elegant way to compare double.
Importants:
I am not going to round down with x significant figures. I have already provide this solution in my question, my question is: Even round down to x significant figures, it will return true when comparing them.
Again
I am not finding a way to round down or truncate the doubles to x significant digits. I have no problem on this part.
Answer
Thanks for #m88 answer. But it still cannot solve my problem.
I finally solve this issue using sigma. (Reference: http://forums.codeguru.com/showthread.php?506300-float-double-value-comparison-significant-figures.)
Thanks to some people misunderstand the problem and vote it as a duplicated question. I can't post my answer for others facing the same problem. So I post the answer in my question. I hope it can help others.
public static int CompareTo(this double value1, double value2, int decimals)
{
var diff = value1 - value2;
var sigma = Math.Pow(10, -decimals - 1);
return Math.Abs(diff) < sigma ? 0 : diff > 0 ? 1 : -1;
}
If you use the Math.Round method to round a and b to 4 decimals, a (0.7045) will always be greater than b (0.7044):
const double a = 0.70448;
const double b = 0.70441;
if (Math.Round(a, 4) > Math.Round(b, 4))
...
If you want to truncate the values, you need to be aware of the fact that not all fractions can be accurately represented in a double. If you want "exact" truncating, you might consider converting the double value to a string, truncate the string and then convert the truncated string value back to double. Something like this:
private static double Truncate(double d, int decimals)
{
string s = d.ToString(System.Globalization.CultureInfo.InvariantCulture);
int index = s.IndexOf(System.Globalization.CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator);
if (index > -1)
return Convert.ToDouble($"{s.Substring(0, index + 1)}{s.Substring(index + 1, decimals)}", System.Globalization.CultureInfo.InvariantCulture);
return d;
}
Usage:
const double a = 0.70448;
const double b = 0.70441;
if (Truncate(a, 4) >= Truncate(b, 4))
....
Obviously, if you don't want any "floating issues" as you said in the chat, you cannot work with floating point data types.
You want to truncate, not round:
double a = Math.Truncate(100 * 0.70448) / 100;
double b = Math.Truncate(100 * 0.70441) / 100;
if (a > b)
{
// ...
}
Note that fractions cannot be accurately represented in a double, as per #mm8's comment.

Floating point division returns integer numbers [duplicate]

This question already has answers here:
Why does integer division in C# return an integer and not a float?
(8 answers)
Closed 6 years ago.
I want to calculate the average of two floating point numbers, but whatever the input, I am getting an integer returned.
What should I do to make this work?
public class Program
{
public static float Average(int a, int b)
{
return (a + b) / 2;
}
public static void Main(string[] args)
{
Console.WriteLine(Average(2, 1));
}
}
There're two problems with your code
Evident one - Integer division - e.g. 1 / 2 == 0 not 0.5 since result must be integer
Hidden one - Integer overflow - e.g. a + b can overflow int.MaxValue and you'll get negative result
The most accurate implementation is
public static float Average(int a, int b)
{
return 0.5f * a + 0.5f * b;
}
Tests:
Average(1, 2); // 1.5
Average(int.MaxValue, int.MaxValue); // some large positive value
The trick is to write the expression as 0.5 * a + 0.5 * b, which also obviates the potential for int overflow (acknowledge Dmitry Bychenko).
Currently your expression is evaluated in integer arithmetic, which means that any fractional part is discarded.
In setting one of the values in each term to a floating point literal, the entire expression is evaluated in floating point.
Finally, if you want the type of the expression to be a float, then use
0.5f * a + 0.5f * b
The f suffix is used to denote a float literal.
return (a + b) / 2F; tells the compiler to treat the number as a float, otherwise it will be treated as an int.
Use this:
public static float Average(int a, int b)
{
return (float)(a + b) / 2;
}
You can use:
(float)(a + b) / 2.0
This will return float
Sorry, if anyone has answered the same way (I did not read all answers)

Method of designing a function to calculate differentiation

I am trying to calculate the numerical differentiation of a particular function. This function may vary (for example, can be a line or a circle).
My first thought is to define a generic function:
delegate double Function(double arg);
static double Derivative(Function f, double arg)
{
double h = 10e-6;
double h2 = h*2;
return (f(arg-h2) - 8*f(arg-h) + 8*f(arg+h) - f(arg+h2)) / (h2*6);
}
For a linear line:
double LinearLine(double arg)
{
double m = 2.0; double c = 1.0;
return m*arg + c;
}
I call:
Function myFunc = new Function(LinearLine);
Derivative(myFunc, 3); //Derivative at x=3
However, in this method I will need to hardcode the m and the c into the LinearLine() function.
Alternatively, if I pass m and c into the LinearLine argument list : LinearLine(double m, double c), I will have to rewrite the Derivative() function return value everytime I call a different function. (For example Circle(double radius, double x, double y)).
My question is in such a case, what would be a good way to design such a class/function?
Note: This answer only applies to constructing functions to pass to Derivative and does not help with implicit functions (as linked by ja72)
You can define functions with lambda expressions:
Func<float,float> myFunc = x = > 3 * x + 7;
You can also curry functions to convert n-ary function to n-1-ary one:
float TwoArg(float x, float y) { return x * y; }
Func<float,float> twoArg2 = x => TwoArg(x, 2);

Categories

Resources