# Tag Info

## Hot answers tagged mathematics

14

if(dimension == 0) { return 0; } Mathematically, that is not correct. The determinant of an empty (i.e. zero-dimensional) matrix is one, see for example What is the determinant of []? on Mathematics Stack Exchange. With respect to efficiency: Your program computes the determinant recursively using the Laplace formula, which requires $O(n!)$ ...

10

double getDeterminant(std::vector<std::vector<double>> vect, int dimension); This will create a copy of the std::vector. For small std::vector this is not a problem, but it's good to make it a habit to pass complex data structures as const&, so the copy will not be created: double getDeterminant(const std::vector<std::vector<double>...

8

The other reviews give some good formatting advice so I'll concentrate solely on the function itself. I would probably write this instead: def dir_diff(dir1, dir2): diff = (dir2 - dir1) % 360 return diff if diff <= 180 else diff - 360 The way Python's % operator works, it assures that we always have a positive number from 0 to 360 for diff in ...

8

A vector of vectors can be an inefficient representation, because the storage may be scattered across many pages of memory. We can keep the data close together by using a single vector, and linearising the rows within it, perhaps like this: #include <cstddef> #include <vector> class Matrix { std::size_t width; std::size_t height; ...

7

I'm not familiar with either Haskell or Python, but I'd like to challenge the way you're tackling this problem. First of all, seven 9s will give you a sum of 7 * 95 = 413343. That's six digits, so searching up to one million (instead of ten million) would already be enough. But we can do better. Instead of analyzing all million numbers, you can reduce that ...

7

Wow! I’ve never reviewed an image before. Neat. First, I’d flip your left square to align the corners of the right-most triangles in the left square with the horizontal line in the right square. This gives a visual indication that those dimensions (a and b) in both squares are the same. With the original image, your eye has to draw the line all the way ...

7

Your comments on the elif / else part are too long to be just after the statements Don't use semicolons (;) in Python. This is a refactored version of the code import math class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int Returns floor(sqrt(x)) """ low = 0 high = x//2 + 1 ...

6

Computation of logsum and logsum1 in gamma() are suboptimal. You do costly operations of raising to power, and recompute factorial on each iteration (the latter invokes the quadratic time complexity BTW). Notice that in the $\sum \dfrac{(-1)^{r-1} k^{r+1}}{(r+1)(r-1)!}$ a consecutive term can be expressed via the previous one, as\$T_{r+1} = -k\dfrac{r+1}{(... 6 Unused header We use nothing from <cmath>, so it need not be included. This should be a function, not a class Putting all code into a class suggests you have a background in Java or similar. In C++, we can (and should) use ordinary functions for operations that are mathematically functions. In this case, we have a pure function: it has no state, ... 6 Calculate Distance To check the distance between points, you can zip together two points to get corresponding coordinates. Every point is denoted by X, Y, Z, so zip(point1, point2) will give you pairs (X1, X2), (Y1, Y2), (Z1, Z2). Furthermore, you can use sum to get the total of any iterable, rather than hard-coding indices. Applying this to your distance ... 6 I normally don't like to do complete rewrites for reviews as I don't think that they're usually helpful. Here though, the major problem that I see with your code is you're trying to do far too much "manually". You aren't making good use of built-in Python constructs that automate some of the painful elements. You also have everything in one massive block. I ... 6 Since you seem to be targeting Sphinx for your documentation you should either: Specify your parameter types correctly in the docstring. :param int dir_1: The direction of the first wind. Or :param dir_1: The direction of the first wind. :type dir_1: int Get Sphinx to do this for you from PEP 484 type hints. (Python 3.5+ notation) def ... 5 To prevent overflow, you need to check if reversed*10+pop > INT_MAX. But in order to avoid actually overflowing while checking, rearrange the equation to reversed > (INT_MAX-pop)/10; Actually, I think you should check against -INT_MIN. Which brings up another point. You could use int64_t for reversed. This both ensures it can hold -INT_MIN before ... 5 The way the problem is decomposed doesn't feel right. In particular, there are too many interfaces, and Additive, Divisible, Negative are unnecessarily disconnected. I recommend to follow a more (mathematically) natural path. The Gram-Schmidt process works in any inner product space (which is by definition a vector space equipped with an inner product), so ... 5 Consolidation and unified conditionals the primary difference dir_2 - dir_1 occurs twice in the initial approach: once at the 1st assignment and another time - in the last if condition. Thus, Extract variable technique can be applied to avoid repetition: prime_diff = final_diff = dir_2 - dir_1 where prime_diff is the primary/initial difference and the ... 4 I agree with Glorfindel that the best result is achieved by thinking of the problem in a different way. Still, improvements can be made to the code that speed it up by about a factor of 3: toDigits :: Int -> [Int] toDigits 0 = [] toDigits x = let (d, m) = x divMod 10 in d seq m : toDigits d isSumofFifth n = n == sum (map (^5) (toDigits ... 4 this is a performance-critical function any replacements will need to keep this requirement in mind Use restrict fusc_word(ulong u, ulong* a, ulong* b) uses a, b and certainly the algorithm does not work if those pointers point to overlapping data. A complier can not make that assumption though and so must emit code as if a and b potentially point to the ... 4 The code The formatting has a number of PEP8 violations. It's not obvious from the name what candidate_range does. It seems to be a wheel for the sieve. Normally that would be inlined in the sieve; even if you prefer not to do that, you could place the function inside sieve to make its scope clear. I don't find sieve_list a very helpful name. In general ... 4 Some observations and guidelines to get you started refactoring the code. Check condition Checking a condition against a bool is rarely written like this in C#: mayBeHigher == false Prefer: !mayBeHigher Refactor variables to allow DRY code If you want to get rid of those if-statements with almost identical bodies, you should refactor your code in a ... 4 Sum generator dis = 0 dis += math.pow((point2[0]-point1[0]),2) dis += math.pow((point2[1]-point1[1]),2) dis += math.pow((point2[2]-point1[2]),2) can be dis = sum((p2 - p1)**2 for p1, p2 in zip(point1, point2)) Type hints PEP484 type hints will help the static analysis and readability of your code. For example, def calculate_distance(... 4 One should almost never use a bare except clause. It should always list the exceptions to be caught. The code would be easier to read and understand, if it were written in section that each tested one aspect of a magic square. Like, is is a square, does it have all the numbers in sequence, do the rows add up to the magic number, do the columns, do the ... 4 Toward optimized functionality and design since all crucial attributes x, y, x_mean, y_mean are initialized on LinearReg instance creation (within __init__ method) - no need to duplicate and define them as class attributes (x = [] ... y = []), those should be removed as redundant raise Error - Error is not Python exception class. Use Exception or ValueError ... 4 Style As far as style goes, your code looks clean and readable, and follows the conventions, so good job for that. You may want to include documentation comments with \\\ four your class and methods. Although the method names are descriptive enough in this rather simple case, it is a good habit to take on. Tests It's nice you use a test framework to test ... 3 Actually, you did a much better job with your first version than you seem to think. Your Python version takes about 23 seconds (Python 3) on my desktop. If I take your original program: toDigits :: Int -> [Int] toDigits 0 = [] toDigits x = toDigits (x div 10) ++ [x mod 10] isSumofFifth n = n == sum (map (^5) (toDigits n)) main = print$ sum (...

3

Distance In both your step(...) functions, you are computing distance(st, vec2(0.5)). If you computed this once, and stored this in a local variable, you'd be able to reuse this computed value, which should save time in your shader. But ... wait a second ... vec2 toCenter = vec2(0.5)-st; float radius = length(toCenter)*2.0; You've already computed this ...

3

Function TirNoPer360(Cash, Dates As Range, rate As Double) The function is implicitly Public, implicitly returns a Variant, and implicitly receives all its parameters ByRef; Cash is implicitly a Variant, and the name isn't making it obvious that... If Opt(Cash, Dates, rate) ... Function Opt(Caja, Fecha As Range, tasa As Double) '... For i = 1 To ...

3

I would use uint64_t even if the API asks for an unsigned long. It's far more precise about what it is, and you can always ensure that both are the same. Assuming your C version is >= GNU C11 you can use the following code just below your #includes (actually anywhere, but I like it on top): _Static_assert(__builtin_types_compatible_p(uint64_t, unsigned ...

3

If you need a type with exactly 64 bits, use uint64_t (from <stdint.h>). That will give a clear compilation error if no such type is available. Given that the function never returns anything other than zero, we can move the cleanup of n, n0 and n_max outside the loop, and simply break to reach them. Is indefinite looping really a good output if a ...

3

The most expensive operation you're performing is calculating a^(rk) every iteration. Since you are doing this in a loop and increasing the exponent by a constant amount each iteration (k), you can replace the exponentiation with a multiplication. This makes your concurrent task function look like this: go func(receiver chan int64, rGiven, k int64) {...

3

My Linear Algebra is a bit rusty, but I think that your terminology is a bit off: public class GramSchmidtProcess<VCT, IPT, FT> { … /** * Performs the Gram-Schmidt process upon {@code basis}. * * @param basis the basis to process. * @return the orthogonal basis. */ public Vector<VCT>[] process(Vector<VCT&...

Only top voted, non community-wiki answers of a minimum length are eligible