Integration of a peaked multidimensional function

I have the following function

PQ=p^2 + q^2 + μ - 2*p*q*(Cos[θp]*Cos[θq] + Cos[ϕ]*Sin[θp]*Sin[θq]) QK=k^2 + q^2 + μ - 2*k*q*Cos[θq] KPQ=k^2 + p^2 + q^2 + 2*p*Cos[θp]*(k - q*Cos[θq]) - 2*q*(k*Cos[θq] +    p*Cos[ϕ]*Sin[θp]*Sin[θq])  vol = p^2*q^2*Sin[θp]*Sin[θq];  denFreq = ω + (k^2 + q^2 + KPQ)/2;  f[ω_, η_, k_, p_, q_, θp_, θq_, ϕ_, μ_] = vol*(1/PQ - 1/QK)*   ((HeavisideTheta[kF - Sqrt[KPQ]]*denFreq)/(PQ*(denFreq^2 + η^2))) 

where I introduced $ \mu$ to regularize the divergence of the integrand. I should check whether the integral converge to a finite limit when $ \mu\rightarrow 0$ .

So I tried to compute the following integral (for small $ \mu$ )

kF = 1.;  ω0 = 0;  η0 = 0.1;  μ0 = 0.0001;  k0 = 0.5;  kcut = 10;  NIntegrate[f[ω0, η0, k0, p, q, θp, θq, ϕ, μ0], {p, kF, kcut},    {q, 0, kF}, {θp, 0, Pi}, {θq, 0, Pi}, {ϕ, 0, 2*Pi},    Method -> "MonteCarlo"] 

I tried different integration schemes (mainly different montecarlo schemes, including the Cuba library) but I obtain quite different results, since I guess even after the regularization with $ \mu$ the function is not “well-behaved”.

Which integration scheme is the most recommended for my case? Taking smaller values of $ \mu$ I find that the integral increases, but how can I be sure that it is the “real” behaviour of the function and not simply a consequence of a not converged numerical integration?

Any suggestion is welcome

Sacar promedio de cada una de las filas de un arreglo multidimensional C++

Estas son las instrucciones del programa:

  1. El programa preguntará cuántos alumnos hay en el grupo y cuántos conceptos se van a evaluar.
  2. El programa pedirá las calificaciones de cada uno de los estudiantes.
  3. Al finalizar, el programa calculará y mostrará el promedio de cada alumno y el promedio general del grupo.

Nada más tengo problemas al momento de sacar el promedio ya que todo lo que he intentado no funciona. Este es el código que he realizado:

using namespace std;  int main (){     int matriz [100][100];     double alumnos;     double conceptos;     int suma;     double promedio;     int contador=0;      cout<<"BIENVENIDO A LA CALCULADORA DE PROMEDIOS";     cout<<"\nIngrese el numero de alumnos: ";     cin>>alumnos;     cout<<"\nIngrese el numero de conceptos: ";     cin>>conceptos;      //Almacenando calificaciones     for (int i=0; i<alumnos;i++){         for (int j=0; j<conceptos;j++){             cout<<"\nDigite la calificacion del alumno "<<i+1<<" en el concepto " << j+1<<": ";             cin>>matriz[i][j];          }     }      for (int i=0; i<alumnos;i++){         for (int j=0; j<conceptos;j++){             suma=suma+ matriz[i][j];          }     }   } 

Les agradecería mucho su ayuda para hacer un ciclo que saque los promedios de cada una de las filas (alumnos).

Cómo extraer Nros Repetidos de un array multidimensional y colocarlos en una tabla html?

Necesito extraer los numeros repetidos de un array llenado por una Consulta mysql. He hecho la consulta y la agrego a un array y si hago un echo pre me muestra el array multidimensional pero necesito sacar todos los numeros que se repiten en esos sub arrays y luegos meterlos en una tabla html que diga “repetidos” y Cantidad de veces que se repiten”

He hecho esto hasta ahora :

$  sql = "SELECT Nro1,Nro2,Nro3,Nro4,Nro5,Nro6 FROM tablanumeros"; $  resultado = mysqli_query($  conexion, $  sql); $  datos = array(); if (mysqli_num_rows($  resultado) > 0 ) {  while ($  row = mysqli_fetch_assoc($  resultado)) {      $  datos[] = $  row;  } 

}

foreach ($ datos as $ dato) {

echo '<pre>'; print_r($  dato); echo '</pre>'; 

Desde ya Gracias a todos

Como recorrer correctamente un arreglo Multidimensional Node JS

Estoy trabajando en Node Js y no entiendo como ordenar correctamente el siguiente arreglo todas las consultas si traen datos,lo comprobe por medio de consola pero en el ciclo cuando lo recorre (asig[k]) me devuelve el ultimo dato del arreglo multidimensional como undefined, pero cuando lo hago estatico (asig[0]), si me devuelve el valor correcto.

const estudiante = await pool.query('select ID_Estudiante from estudiante order by ID_Estudiante desc limit 1');  const asig = await pool.query('SELECT ID_ACC FROM asignacion_cursos_catedratico WHERE Grado_ID_Grado= ? AND Año_ID_Anio = ?', [Grado_ID_Grado, ID_Anio]);  const bim = await pool.query('SELECT ID_Bimestre FROM bimestre');       for (var k = 0; k <= 4; k++) {        var valus = [         bim[0], estudiante, asig[k],         bim[1], estudiante, asig[k],         bim[2], estudiante, asig[k],         bim[3], estudiante, asig[k]         ]     } 

How to find similar records using multidimensional array?

I have table that describes a movie release. This table consists of columns:

  • movie_id int
  • release_day int
  • showtime_count int
  • ticket_sold_count int

e.g. (1, 1, 100, 200) tuple describes movie ID 1, on the first day of the movie release when it had 100 showtimes and sold 200 tickets.

I have a movie that is 5 days into the release (e.g. (2,1,100,200), (2,2,150,300), (2,3,100,250), (2,4,150,300), (2,5,100,250)) and I want to find previous releases that have performed similarly up to this day into their release.

I know that I can calculate a distance between two points using <->. But how would I index and search the entire database for a movie where distance for days 1, 2, 3, 4 and 5 is the lowest?

Declaring multi-dimensional array using CFG

I am still juveline to compilers and formal languages. I’ve tried to write context-free grammar (CFG) for a multi-dimensional array, but I am not sure of my solution, so could you suggest your CFG for multi-dimensional array?

<type>:: = int | float | string <array>:: = <type> [<identifier>] | <array> | [<identifier>]  <identifier>::= <letter> | <identifier><letter>|<identifier><digit> <letter>::= a|...|z <digit>::= 0|...|9 

Is this implementation is a true one for multi-dimensional array?

My second question is regarding function invocation as well? I have written the following declaration for function:

<funDeclaration>::= <type> <identifier>(<params>) <statement> | <identifier> (<params> )<statement> 

Without demonstrating , just for clarity and to keep the question short, how to write function invocation?

Convertir json en json multidimensional

Tengo un JSON con la siguiente estructura:

[     {"Model":"6"},     {"Title":"tituloM6","Value":"saddsaf"},     {"Title":"msgOperadorM6","Value":"sdafdsfa"},     {"Title":"msgErrorM6","Value":"sadsdafdf"},     {"Title":"ok","Value":""},     {"Title":"imgM6","Value":""},     {"Model":"6"},     {"Title":"tituloM6","Value":"asdsf"},     {"Title":"msgOperadorM6","Value":"asdsddf"},     {"Title":"msgErrorM6","Value":"dsafsfdsfda"},     {"Title":"ok","Value":""},     {"Title":"imgM6","Value":""} ] 

Pero no logro transformarlo en uno multidimensional con la siguiente estructura:

[     {"Model":"6"},     {"datos":          [             {"Title":"tituloM6","Value":"saddsaf"},             {"Title":"msgOperadorM6","Value":"sdafdsfa"},             {"Title":"msgErrorM6","Value":"sadsdafdf"},             {"Title":"ok","Value":""},             {"Title":"imgM6","Value":""}         ]            }      {"Model":"6"},     {"datos":          [             {"Title":"tituloM6","Value":"asdsf"},             {"Title":"msgOperadorM6","Value":"asdsddf"},             {"Title":"msgErrorM6","Value":"dsafsfdsfda"},             {"Title":"ok","Value":""},             {"Title":"imgM6","Value":""}         ]     }    ] 

El json lo obtengo de un List<string> y lo convierto con:

var json = JsonConvert.SerializeObject(lista); 

He tratado de realizarlo con un foreach que recorriese los elementos de la lista y con dos List<>, una para Model y otra para los otros campos y despues unirlas de la siguiente manera:

List<string> modelos = new List<string>(); List<string> valores = new List<string>(); bool primero = false;      foreach (var resultado in result) {     if (resultado.Model != null)     {         modelos.Add("Modelo");         modelos.Add(resultado.Model);         if (primero != false)         {             modelos.AddRange(valores);             valores = new List<string>();         }                }     else     {         valores.Add(resultado.Title);         valores.Add(resultado.Value);     }     primero = true; } 

¿Cómo puedo generarlo?

Does the order of multidimensional array’s length affect the time complexity of accessing elements?

I was using a 3d array in java of lengths 3001,3001,4 in a dp problem but I couldn’t get my submission accepted as i kept on exceeding the time limit(1 second), i checked the code of a friend and found out that the only difference was that the order of the lengths of the memo was 4,3001,3001 as soon as i changed my memo order to the previous order my code ran in 400ms so i would like to know what is the difference between both cases

Padding multi-dimensional array to its max shape

For some machine learning purpose, I need to work with sequences with different lengths. To be able to process efficiently those sequences, I need to process them in batches of size size_batch. A batch typically has 4 dimensions and I want to convert it to a numpy’s ndarray with 4 dimensions. For each sequence, I need to pad with some defined pad_value such that each element has the same size: the maximal size.

For example with 3 dimensional input:

[[[0, 1, 2],   [3],   [4, 5]],  [[6]],  [[7, 8],   [9]]] 

desired output for pad_value -1 is:

[[[0, 1, 2],   [3, -1, -1],   [4, 5, -1]],  [[6, -1, -1],   [-1, -1, -1],   [-1, -1, -1]]  [[7, 8, -1],   [9, -1, -1],   [-1, -1, -1]]] 

which has shape (3, 3, 3). For this problem, one can suppose there are no empty list in the input. Here is the solution I came up with:

import numpy as np import itertools as it from typing import List  def pad(array: List, pad_value: np.int32, dtype: type = np.int32) -> np.ndarray:     """ Pads a nested list to the max shape and fill empty values with pad_value      :param array: high dimensional list to be padded     :param pad_value: value appended to     :param dtype: type of the output     :return: padded copy of param array     """     # Get max shape     def get_max_shape(arr, ax=0, dims=[]):         try:             if ax >= len(dims):                 dims.append(len(arr))             else:                 dims[ax] = max(dims[ax], len(arr))              for i in arr:                 get_max_shape(i, ax+1, dims)         except TypeError:  # On non iterable / lengthless objects (leaves)             pass          return dims      dims = get_max_shape(array)      # Pad values     def get_item(arr, idx):         while True:             i, *idx = idx             arr = arr[i]             if not idx:                 break         return arr      r = np.zeros(dims, dtype=dtype) + pad_value     for idx in it.product(*map(range, dims)):         # idx run though all possible tuple of indices that might          # contain a value in array         try:             r[idx] = get_item(array, idx)         except IndexError:             continue      return r 

It does not feel really pythonic but does the job. Is there any better way to do it I should know ? I think I might be able to improve its speed by doing smart breaks in the last loop but I haven’t dug much yet.

Thanks !