Multiplying two double value gives negative number in flutter - flutter

I need to multiply two large numbers for example,
double x = 318191400000;
double result =x*x;
But i am getting negative value for this when building in flutter .
Please help me on this.
[1]: https://i.stack.imgur.com/eyxJ4.png

You're not actually multiplying two doubles here, but two ints which is overflowing the 64-bit integer resulting in a negative number.
With doubles:
void main() {
double x = 318191400000;
print(x*x); // Result: 1.0124576703396e+23
}
With ints:
void main() {
int x = 318191400000;
print(x*x); // Result: -8411186631728820224
}
If you ever print a double to the console, you'll always see it displayed in either scientific notation (for extremely large or small values) or with a decimal point with at least one trailing digit.

Finally i have found solution and sharing here for anyone having these kind of issues,
xValues[index].toDouble() * yValues[index].toDouble()
This gives the expected result which is 1.0124576703396e+23

Related

Why . sign used before number? in Dart/flutter

What means sign . before number in Dart languge
exemple (.59):
double width = .59 * MediaQuery.of(context).size.width;
A decimal point, in other words it implies a leading zero.
e.g.
print((.23.toStringAsFixed(3)));
output:
0.230
And;
var n = .34;
print (n.runtimeType);
will print double.
(though I don't see it specifically stated in the double class documentation, and not sure if that would be affected by locale/culture settings)

DIY rounding function gives weird values [duplicate]

This question already has answers here:
How do you round a double in Dart to a given degree of precision AFTER the decimal point?
(28 answers)
Closed 10 months ago.
I've coded this simple function to round doubles to a custom step size.
The normal .round() function retuns an int and can only rounds to the nearest 1.
My function returns a double and can round to the nearest 100.0, 5.0, 1.0, 0.1 or 0.23, you get it.
But when I put in certain doubles the result doesn't really work out and is a very tiny fraction off.
I think this has something to do with how computers do floating comma calcualations, but I need an efficient way to get around it.
Run on DartPad
void main() {
stepround(61.337551616741315, 0.1); // this should be 61.3 but is 61.300000000000004
}
/// rounds a double with given steps/precision
double stepround(double value, double steps) {
double rounded = (value / steps).round() * steps;
print(value.toString() + " rounded to the nearest " + steps.toString() + " is " + rounded.toString());
return rounded;
}
As mentioned in the comments, the cause of this issue the way that computers deal with floating numbers. Please refer to the links in the comments for further explanation.
However in a nutshell the problem is mostly caused when dividing or multiplying decimals with decimals. Therefore we can create a similar method to the one you created but with a different approach. We we will take the precision to be as an int.
I.e: 0.1 => 10; 0.001 => 1000
double stepround(double value, int place){
return (value * place).round() / place;
}
Example
// This will return 61.3
stepround(61.337551616741315, 10);
// This will return 61.34
stepround(61.337551616741315, 100);
// This will return 61.338
stepround(61.337551616741315, 1000);
This method works since the small fraction that is caused by the multiplication is removed by round(). And after that we are doing a division by an integer which doesn't create such a problem.

how to convert negative int to positive int in flutter

for example if i have a list like
List list = [-12,3,-24,58,12];
i have already tried this ,i did not understand it https://stackoverflow.com/questions/55374813/why-abs-function-in-dart-return-negative-number-when-not-wrapped-in-parenthesi\
i want to convert all parameters to a positive parameters
or if i had only a integer which is negative how to convert it to a positive integer
if you need more information please let me know and thanks for the helps
You can use Abs method for numbers to get absolute value:
int number = -5;
print(number.abs()); // prints: 5
https://dart.dev/guides/language/language-tour#numbers

Swift: Double conversion inconsistency. How to correctly compare Doubles?

I have a very simple function to convert temperature from ˚C TO ˚K.
func convertKelvinToCelsius(temp:Double) ->Double {
return temp - 273.15
}
And I have a unit test to drive this function. This is where the problem is:
func testKelvinToCelsius(){
var check1 = conv.convertKelvinToCelsius(200.00) // -73.149999999999977
var check2 = 200.00 - 273.15 // -73.149999999999977
var check3 = Double(-73.15) // -73.150000000000006
//Passes
XCTAssert(conv.convertKelvinToCelsius(200.00).description == Double(-73.15).description, "Shoud convert from celsius kelvin")
//Fails
XCTAssert(conv.convertKelvinToCelsius(200.00) == Double(-73.15), "Shoud convert from celsius kelvin")
}
When you add a breakpoint and check the values of check1, check2 and check3, they are very interesting:
check1 Double -73.149999999999977
check2 Double -73.149999999999977
check3 Double -73.150000000000006
Questions:
Why does Swift return different values for check1/check2 and check3
How can I get the second test to pass, because writing it like I did the test1 smells. Why should I have to convert Doubles to Strings to be able to compare them?
Finally, when I println check1, check2 and check3, they all print to be '-73.15'. Why? Why not print accurately, and not confuse the programmers!?
To Reproduce:
Just type 200 - 273.15 == -73.15 in you playground and watch it go false!!
This is expected behavior for floating point values. They cannot be 100% accurately represented.
You can use the XCTAssertEqualWithAccuracy function to assert floating point values are within a given range of each other.
The reason println prints the same value for all is because it internally rounds them to two decimals (I assume).
This is not a Swift specific issue, this is related to the fact how decimal numbers are created in computers and what is their precision. You will need to work with DBL_EPSILON.
Swift, like most languages, uses binary floating point numbers.
With binary floating point numbers, some numbers can be represented exactly, but most can't. What can be represented exactly are integers unless they are very large (for example, 100000000000000.0 is fine), and such integers multiplied or divided by powers of two (7.375 is fine, it is 59.0 / 8, but 7.3 isn't).
Every floating point operation gives you the exact result, rounded to the nearest floating-point number. So you get
200.0 -> Exactly 200
273.15 -> A number very close to 273.15
200 - 273.15 -> A number very close to -73.15
-73.15 -> A number very close to -73.15
If you compare two numbers that are both very very close to -73.15 they are not necessarily equal. That's not a problem of the == operator; that one will determine correctly whether they are equal or not. The problem is that the two numbers can actually be different.

Inaccurate division of doubles (Visual C++ 2008)

I have some code to convert a time value returned from QueryPerformanceCounter to a double value in milliseconds, as this is more convenient to count with.
The function looks like this:
double timeGetExactTime() {
LARGE_INTEGER timerPerformanceCounter, timerPerformanceFrequency;
QueryPerformanceCounter(&timerPerformanceCounter);
if (QueryPerformanceFrequency(&timerPerformanceFrequency)) {
return (double)timerPerformanceCounter.QuadPart / (((double)timerPerformanceFrequency.QuadPart) / 1000.0);
}
return 0.0;
}
The problem I'm having recently (I don't think I had this problem before, and no changes have been made to the code) is that the result is not very accurate. The result does not contain any decimals, but it is even less accurate than 1 millisecond.
When I enter the expression in the debugger, the result is as accurate as I would expect.
I understand that a double cannot hold the accuracy of a 64-bit integer, but at this time, the PerformanceCounter only required 46 bits (and a double should be able to store 52 bits without loss)
Furthermore it seems odd that the debugger would use a different format to do the division.
Here are some results I got. The program was compiled in Debug mode, Floating Point mode in C++ options was set to the default ( Precise (/fp:precise) )
timerPerformanceCounter.QuadPart: 30270310439445
timerPerformanceFrequency.QuadPart: 14318180
double perfCounter = (double)timerPerformanceCounter.QuadPart;
30270310439445.000
double perfFrequency = (((double)timerPerformanceFrequency.QuadPart) / 1000.0);
14318.179687500000
double result = perfCounter / perfFrequency;
2114117248.0000000
return (double)timerPerformanceCounter.QuadPart / (((double)timerPerformanceFrequency.QuadPart) / 1000.0);
2114117248.0000000
Result with same expression in debugger:
2114117188.0396111
Result of perfTimerCount / perfTimerFreq in debugger:
2114117234.1810646
Result of 30270310439445 / 14318180 in calculator:
2114117188.0396111796331656677036
Does anyone know why the accuracy is different in the debugger's Watch compared to the result in my program?
Update: I tried deducting 30270310439445 from timerPerformanceCounter.QuadPart before doing the conversion and division, and it does appear to be accurate in all cases now.
Maybe the reason why I'm only seeing this behavior now might be because my computer's uptime is now 16 days, so the value is larger than I'm used to?
So it does appear to be a division accuracy issue with large numbers, but that still doesn't explain why the division was still correct in the Watch window.
Does it use a higher-precision type than double for it's results?
Adion,
If you don't mind the performance hit, cast your QuadPart numbers to decimal instead of double before performing the division. Then cast the resulting number back to double.
You are correct about the size of the numbers. It throws off the accuracy of the floating point calculations.
For more about this than you probably ever wanted to know, see:
What Every Computer Scientist Should Know About Floating-Point Arithmetic
http://docs.sun.com/source/806-3568/ncg_goldberg.html
Thanks, using decimal would probably be a solution too.
For now I've taken a slightly different approach, which also works well, at least as long as my program doesn't run longer than a week or so without restarting.
I just remember the performance counter of when my program started, and subtract this from the current counter before converting to double and doing the division.
I'm not sure which solution would be fastest, I guess I'd have to benchmark that first.
bool perfTimerInitialized = false;
double timerPerformanceFrequencyDbl;
LARGE_INTEGER timerPerformanceFrequency;
LARGE_INTEGER timerPerformanceCounterStart;
double timeGetExactTime()
{
if (!perfTimerInitialized) {
QueryPerformanceFrequency(&timerPerformanceFrequency);
timerPerformanceFrequencyDbl = ((double)timerPerformanceFrequency.QuadPart) / 1000.0;
QueryPerformanceCounter(&timerPerformanceCounterStart);
perfTimerInitialized = true;
}
LARGE_INTEGER timerPerformanceCounter;
if (QueryPerformanceCounter(&timerPerformanceCounter)) {
timerPerformanceCounter.QuadPart -= timerPerformanceCounterStart.QuadPart;
return ((double)timerPerformanceCounter.QuadPart) / timerPerformanceFrequencyDbl;
}
return (double)timeGetTime();
}