C# - Infinite numbers - c#

I'm currently work on a certain program (in C# .NET - winforms), and among the things i came across the following problem:
I need to calculate the point (t, f(t)) given that:
f(t) = [Sin(t) / 16*Cos^4(t)]^(1/3), Such that: t: -89.995 -> 89.995. (t is real number).
Note: the value of t is ranges from -89.995 to 89.995.
I use the .NET functions Math.Sin(), Math.Cos(), Math.Pow() for the calculations, the converssions from radians to degrees are correct and all right.
The problem is that for every t < 0 that i put in f(t) i got NaN ( = not a number) from the above functions, and when i calculate it in a standard calculator i get standard correct values.
For examplae: t = -0.9165664, f(t) = -0.1000096, (Taht's the correct result).
but when i use the .NET functions in my program, the result i get for t = -0.9165664 is NaN (= Not a Number), why? it's not an exeption, not dividing by zero or something like that.
The code i use in the program:
float t = -0.9165664;
float numerator = Math.Sin(t * Math.PI / 180.0f);
float denominator = 16.0f * Math.Pow(Math.Cos(t * Math.PI / 180.0f), 4)
float ft = (float)Math.Pow(numerator / denominator, 1.0f / 3.0f));
Note: I can't cahnge the type of ft to double.
When i put any t > 0 in the above code it gives the correct result.
Can someone explain me what wrong or suggest a possible solution?
Thanks for help!!!

The problem is the definition of the Math.Pow function, see the documentation. Since your exponent is fixed and you're looking for the 3rd root as a real number, try something like
float t = -0.9165664;
float numerator = Math.Sin(t * Math.PI / 180.0f);
float denominator = 16.0f * Math.Pow(Math.Cos(t * Math.PI / 180.0f), 4)
float val = numerator / denominator;
float ft = Math.Sign(val) * (float)Math.Pow(Math.Abs(val), 1.0f / 3.0f));

Related

How do i convert Floor in excel to Unity Mathf?

How do i convert Floor in excel to Unity Mathf? I have a procedural equations like this in Excel:
= FLOOR(MOD(5, 20) * 0.2, 1)
and i want to convert it to C# Script but i can't. I have already tried:
float test = Mathf.Floor((5 % 20) * (1 / 5));
But it's not what i want. The answer that i want is 1 (Like the result from Excel) but in C# Script it is 0. Please give me some suggestions and thanks for that!
1 / 5
is an integer division with result 0! Therefore
Mathf.Floor((5 % 20) * 0);
is obviously also 0.
You should either use a float division by simply using a float value for at least one of the two operands
1f / 5f
or why not simply directly use the float value
0.2f
so your line should be
float test = Mathf.Floor(5 % 20 * 0.2f);
Note: If you would like to get the result directly as an int value you might want to use Mathf.FloorToInt instead.
Just for completeness: Excel's FLOOR has a second parameter significance
The multiple to which you want to round.
In order to also fake that in your line you would do
var result = Mathf.Floor(5 % 20 * 0.2f / significance) * significance;

Regarding Binary to Float Conversion in c# program

float resultInteger = 0.0f;
float power = 1/2.0f;
for (i = highPointPosition+1; i <= highResultIndex; i++, power /= 2
resultInteger += result[i] * power;
power = 1.0f;
for (i = highPointPosition, power = 1.0f; i >= 0; i--, power *= 2)
resultInteger += result[i] * power;
if (carry == 1)
resultInteger += carry * power;
The above code converts binary to floating point number.
I have been given an assignment asking me to convert two floating point numbers to binary and then adding them and then converting the result to float.
In the above code when I perform 3.5 + 5.39 the result should be 8.89, but instead it is 8.889999.
For others like 9.5 + 7.39 the answer is right i.e., 16.89.
Can Anyone help explain why I am encountering such problem?
Binary can't expression 1/10 in decimal accurately, like how base 10 can't expression 1/3 accurately, while base 12 can (1 third is 0.4 in base 12).
Normally, if you want to get better math accuracy, you would use decimal to do the math instead, like this:
decimal x = 2.5M;
decimal y = 1.19M;
Console.WriteLine(x + y);
decimal works because it calculates in base ten, not binary. However, if your professor is asking you to do convert into binary to do the math, then it doesn't matter what the initial type was. It will never be possible to get the correct result with binary.
It happens for the reason that 1/10 can't be expressed accurately in binary system.
You can try the following:
float a = 3.5f;
float b = 5.39f;
Console.WriteLine(Math.Round(a + b, 2));
Console.ReadLine();
Use Math.Round(value, digits), you can get the result you want.

How to convert percent slope to degree

double mypercentslope = 1
With a calculator if I wanted to convert that to a degree, I'd simply do: arctan(0.01);
I've tried Math.Atan(0.01) and it's reporting an incorrect value. I've read that c# uses radians but not sure, based on that, how to accomplish what i need. Thanks all!
Yes, Math.Atan does give it's result in radians (from here). You could use this to convert to degrees:
private double RadianToDegree(double angle)
{
return angle * (180.0 / Math.PI);
}
(the above code snippet is taken from here)
so full working code might look like:
double myPercentSlope = 100;
double rads = Math.Atan(myPercentSlope/100);
double degrees = rads * (180.0 / Math.PI);

Get the inverse of a function, millibels to percentage & percentage to millibels

Audio noob here and math challenged. I'm working with DirectSound which uses a -10000 to 0 range, converting that to a 0-100 scale.
I found this function here to obtain the millibels based on a percentage:
private int ConvertPercentageToMillibels(double value)
{
double attenuation = 1.0 / 1024.0 + value / 100.0 * 1023.0 / 1024.0;
double db = 10 * Math.Log10(attenuation) / Math.Log10(2);
return (int)(db * 100);
}
I need help getting the inverse of this function, basically to get the percentage based on millibels. Here is what I've got so far, which isn't working:
private double ConvertMillibelsToPercentage(int value)
{
double db = value / 100;
double attenuation = Math.Pow(10, db) / 10 * Math.Pow(10, 2);
double percentage = (1.0 * attenuation) - (1024.0 * 100.0 / 1023.0 * 1024.0);
return percentage;
}
Here you go!
private double ConvertMillibelsToPercentage(int value)
{
double exponent = ((value / 1000.0) + 10);
double numerator = 100.0 * (Math.Pow(2, exponent) - 1);
return numerator / 1023.0;
}
Answer will differ slightly due to obvious issues that arise from going between an int and a double.
EDIT: Per the teach how to fish request, here are the first mathematical steps toward arriving at the solution. I didn't show the whole thing because I didn't want to spoil allll the fun. All log functions should be considered Log base 10 unless otherwise noted:
millibels = db*100; // Beginning to work backward
millibels = 10*Log(attenuation)*(1/Log(2))*1000; // Substituting for db
millibels = 1000*Log(attenuation)/Log(2); // Simplifying
let millibels = m. Then:
m = 1000*Log(attenuation)/Log(2);
from here you can go two routes, you can either use properties of logs to find that:
m = 1000* Log_2(attenuation);// That is, log base 2 here
attenuation = 2^(m/1000);
OR you can ignore that particular property and realize:
attenuation = 10^(m*Log(2)/1000);
Try to work it out from one of the above options by plugging in the value that you know for attenuation:
attenuation = (1/1024)+(percentage/100)*(1023/1024);
And then solving for percentage. Good luck!
PS If you ever get stuck on things like this, I highly recommend going to the math stack exchange - there are some smart people there who love to solve math problems.
OR if you are particularly lazy and just want the answer, you can often simply type this stuff into Wolfram Alpha and it will "magically" give you the answer. Check this out

Find closest city to given location

I am trying to find the closest city to given location. I have stored location of some cities that I want to work with. And I have my location, but I dont know how to find the closest city to my location ?
Cities
New York - Lat 40.714353; Long -74.005973
Washington - Lat 38.895112; Long -77.036366
....more cities
My location
Philadephia - Lat 39.952335; Long -75.163789
So how should I compare the coords to find the closest city ? I am doing program in C# but just knowing the solution of algorythm is enaught for me :)
Thanks for any help
You should use your high school knowledge to solve this problem, your alghorithm is:
closest = sqrt ( (lat2 - lat1) ^2 + (Long2-Long1) ^2 )
now this give you your air distance.
so, when you do this for an array of values, you can use asort function to compare which one is closest to you.
Strictly, you'd want to use the Haversine formula.
However, while you could perhaps be just slightly out in far northern or far southern points, you could probably get by by pretending that Mercator projections are accurate for distance, and ignoring the curvature of the earth. This is especially true if you are going to have lots of cities, as the error is greater, the further points are from the target point. Hence you would just use Pythagoras':
relDist = √((xLat - yLat) × (xLat - yLat) + (xLng - yLng) × (xLng - yLng))
But since you only care about (and only get) a relative ordering, you can skip the square-root bit, which is the heaviest step:
relDist = (xLat - yLat) × (xLat - yLat) + (xLng - yLng) × (xLng - yLng)
As well as being faster in and of itself, it can also be reasonably preformed on integers, should you store your coordinates as multiples of the actual coordinate (e.g. storing New York's (40.664167, -73.938611) as the pair (406642, -739386). This can be a big boost if you want to quickly sort a large number of places in order of proximity to a given point.
If however you really care about precision in the face of the fact that the earth is round, then the following implements Haversine:
private const double radiusE = 6378135; // Equatorial radius
private const double radiusP = 6356750; // Polar radius
private const double radianConv = 180 / Math.PI;
public static double GetDistanceBetweenPoints(double lat1, double long1, double lat2, double long2)
{
double dLat = (lat2 - lat1) / radianConv;
double dLong = (long2 - long1) / radianConv;
double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(lat2) * Math.Sin(dLong/2) * Math.Sin(dLong/2);
return Math.Sqrt((Math.Pow(radiusE * radiusP * Math.Cos(lat1 / radianConv), 2)) / (Math.Pow(radiusE * Math.Cos(lat1 / radianConv), 2) + Math.Pow(radiusP * Math.Sin(lat1 / radianConv), 2))) * (2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a)));
}
The distance bitween two points (x1, y1) and (x2, y2) is
d = sqrt((x1 - x2) ^ 2 + (y1 - y2) ^ 2)
so in c# you we will have:
public City FindNearestCity(double currentLatitude, double currentLogitude, List<City> cities)
{
Dictionary<City, double> distances = new Dictionary<City, double>();
foreach (City city in cities)
{
double distance = Math.Sqrt(Math.Pow(city.latitude - currentLatitude, 2) + Math.Pow(city.Longitude - currentLogitude, 2));
distances.Add(city, distance);
}
double minimumDistance = distances.Min(distance => distance.Value);
return distances.First(distance => distance.Value == minimumDistance).Key;
}
Visit here
you can find two c# function using Brute force and divide-and-conquer algorithms to find the closest two points among a set of given points in two dimensions.
Jon's answer is very inspiring, although there're few missing pieces.
lat1 should be in a
double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(lat1/ RadianConv) * Math.Cos(lat2/ RadianConv) * Math.Sin(dLong / 2) * Math.Sin(dLong / 2);
The simulated radius in last statement gave 2000ish sometimes, which should be close to either RadiusE or RadiusP, so I used mean radius instead.
return 6371* (2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a)));

Categories