Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get n power ( square of a number or cube etc.) of a number in flutter?

Tags:

flutter

dart

I have two values one for base that is X and one for power N, how can a get X to the power of N ans.

any code will be appreciated.

like image 772
Gudguy Avatar asked Sep 20 '19 18:09

Gudguy


People also ask

How do you find the power of a number in flutter?

if x is -Infinity or -0.0 and y is an odd integer, then the result is -pow(-x ,y) . if x is -Infinity or -0.0 and y is not an odd integer, then the result is the same as pow(-x , y) . if y is Infinity and the absolute value of x is less than 1, the result is 0.0.

How do you find the square of a number in darts?

In Dart, the sqrt() function returns the positive square root of a value. It can be used when the dart:math package is imported.


2 Answers

You are looking for this: https://api.dartlang.org/stable/2.5.0/dart-math/pow.html so:

pow(X,N)

If you want to implement it, you can have a look at here: https://coflutter.com/challenges/dart-how-to-implement-exponential-function-power/ This boils down to this loop:

int power(int x, int n) {
  int retval = 1;
  for (int i = 0; i < n; i++) {
    retval *= x;
  }

  return retval;
}

This only works well for integer n-s.

like image 142
g_bor Avatar answered Sep 28 '22 12:09

g_bor


For all of these examples with pow you need the following import:

import 'dart:math';

final answer = pow(8, 2); // 64

Notes:

  • If you are only squaring, then it's probably easier to do this:

    final answer = 8 * 8;
    
  • answer is inferred to be of type num, which could be an int or double at runtime. In this case the runtime type is int, but in the following two examples it is double.

Fourth root of 256

final answer = pow(256, 1/4); // 4.0

0.2^(-3)

final answer = pow(0.2, -3); // 124.99999999999999

That's basically the same as five cubed.

like image 31
Suragch Avatar answered Sep 28 '22 13:09

Suragch